Top 5 vs CODE extensions for web developers

Top 5 vs CODE extensions for web developers:

1. Live Server

A must-have for any developer creating webpages using HTML and CSS. Once installed all you have to do is open your project, look for the Go Live button on the status bar at the bottom, or use the command Alt+L Alt+O in order to launch a quick development live server so you can view your current project live on any browser.

2. GitLens

If you know and work with git, you will want this extension. This customizable extension lets you better understand your code by easily allowing you to view when, why, and by whom the code was added/edited.

3. IntelliSense for CSS class names in HTML

You don’t need to remember all the CSS class names while you are working on your HTML file. This extension will provide you with a completion list for the HTML class attribute based on your workspace or external files referenced beforehand.

Alternative: HTML CSS Support
Complementary: CSS Peek

4. Visual Studio IntelliCode

This extension uses AI technology to help Python, TypeScript/JavaScript, and Java developers. As you code, it will show a recommended completion items list sorted by context, rather than alphabetically or by most recent.

5. Rainbow Brackets

Visual help for those programmers that need to worry about closures, like javascript programmers. It does this by providing different colors for round brackets, square brackets, and squiggly brackets.

Alternative: Bracket Pair Colorizer 2

There is no shame in using tools to help you. Quite the contrary, a smart developer is one that will use these to make their lives easier and become more efficient in the process!

from Tumblr https://generouspiratequeen.tumblr.com/post/627907185916116992

How To Create JavaScript Objects From an Excel File

How To Create JavaScript Objects From an Excel File:

https://damianfallon.blogspot.com/

Well it might surprise you to know that there is a tool that can be installed with a single npm command that allows you to read data from an excel file. I will be showing in this blog how to do this, as well as how to create an object and add insert that object into a SQL database.

There are a lot of reasons this could be useful. For example, suppose a teacher has their student’s grades saved in excel files and you wanted to import them into a JS app automatically. You might have a spreadsheet that looks something like this:

To get started, enter this command into your terminal (You will need Node installed as well. I am using VS code)

npm install read-excel-file

Now, in your JS file, just add this require statement to the top:

const xlsxFile = require('read-excel-file/node');

And that’s the entire setup! The xlsxFile function takes a single argument—the path to your excel file as a string. The file path will be relative to the JS file that the xlsxFile was “required” on. So if you have an excel file named ‘ExcelFile.xlsx’ and it is in the same folder, the path would look something like: ’./ExcelFile.xlsx’

A successful call of the xlsxFile function will return a promise that contains an array of all the rows of your excel file. Each of those rows are also arrays which contain the value of each cell. So to bring it all together:

const xlsxFile = require('read-excel-file/node');

xlsxFile('./ExcelFile.xlsx')
  .then((rows) => {
    rows.forEach((row) => {
      row.forEach((cell) => {
        console.log(cell);
      });
    });
  });

The above function will display every single cell on the console, left to right top to bottom. Now, to manipulate that data into something more useful:

xlsxFile('./ExcelFile.xlsx')
  .then((rows) => {
    const columnNames = rows.shift(); // Separate first row with column names
    const objs = rows.map((row) => { // Map the rest of the rows into objects
      const obj = {}; // Create object literal for current row
      row.forEach((cell, i) => {
        obj[columnNames[i]] = cell; // Use index from current cell to get column name, add current cell to new object
      });
      return obj;
      console.log(objs); // Display the array of objects on the console
    });
  });

Now, each row has been converted to a JavaScript object using the first row as its key names, and every row after used to create an object with key values from their cells and key names of the name at the top of their columns—basically like an excel-to-JavaScript constructor function.

And finally, if you wanted to use an ORM like Sequelize to insert these into a database:

    xlsxFile('./ExcelFile.xlsx')
      .then(async (rows) => {
        const columnNames = rows.shift();
        const promises = rows.map((row) => { // Map the rows array into an array of promises that each create an entry in the DB
          const obj = {};
          row.forEach((cell, i) => {
            obj[columnNames[i]] = cell;
          });
          return Grade.create(obj); // 'Grade' is a hypothetical Sequelize model where the grades can be saved
        });
        await Promise.all(promises); // Use Promise.all to execute all promises
      });

And that’s the tutorial! It should be noted that are limitations to the size of the .xlsx files that can be imported, although they are not explicitly stated by the developer. While this may not be the absolute most practical method of handling data to be switching back and forth between Excel and JavaScript data, it can certainly be useful for small projects and save a lot of time if you needed to update an older data set and import it for a JavaScript project.#

https://damianfallon.blogspot.com/

from Tumblr https://generouspiratequeen.tumblr.com/post/627907183915515904

How to explore a user’s Tweets using v2 of the Twitter API

How to explore a user’s Tweets using v2 of the Twitter API:

 

This tutorial was originally posted to developer.twitter.com

The Twitter API allows you to retrieve and explore the timeline of public Tweets a user has posted. To explore a user’s Tweets you can use recent search to get Tweets from the past seven days.

In this tutorial, you will learn how to:

  • Set an objective for your work
  • Connect and authenticate to the Twitter API
  • Shape your data
  • Build any additional logic or connect to other APIs you are using

Prerequisites

Steps to consider

Step 1: Set an objective for your work

While exploring the Tweets of a user you may want to take a moment to figure out exactly what you will want to accomplish.

  • Creating workflow triggers: A user Tweets x and from there y happens such as if the handle TwitterDev Tweets the words “important change” you can get an email to your work account letting you know what the important change would be.
  • Performing Tweet sentiment: You can also do tasks such as performing Tweet sentiment on your timeline so you can analyze your own Tweets to let you know how positive your week was.

Step 2: Connect and authenticate to the Twitter API

To connect to the Twitter API, you will need to authenticate by passing in your credentials before you can get any data back. At this point, you may want to consider using a library to help you with OAuth such as requests for Python or httparty for Ruby. You should also consider how you want to store your credentials securely. Some options include using environment variables or setting up a configuration file that you can store in your .gitignore file on GitHub.

Be sure to take a look at the authentication section of our documentation. If you lose your credentials or think they may be compromised, you can always regenerate them by navigating to the App in question’s keys and tokens section. Additionally, you can read more about security best practices.

Step 3: Shape your data

You will need to adjust your query to get the right Tweets you want. For example, for the TwitterDev example, you’d want to make sure the endpoint you are making a GET request to is:

You may want to check out our sample code for recent search at this point:

To adjust this for your handle, you would change where it says TwitterDev to another. You can also adjust the query to include only Tweets with images or a certain hashtag. You can learn more about how to craft your query. It’s often helpful to take a step back and figure out which Tweets you wouldn’t want to get back. From there, you can make sure your query includes the appropriate logic to exclude unwanted Tweets.

You also will want to consider how many Tweets you get back, and what fields the data you are looking for is located in. By default, you will get back the id and text of each Tweet. You can make adjustments to this payload by adding additional fields and expansions to your query.

You will also need to consider how many Tweets you will need to perform the task you have in mind. The first 10 Tweets are found in an object called data. To obtain additional Tweets, you need to handle pagination. To do so, you will need to access the next_token from the object called meta and connect to get the additional Tweet objects back for the next 10 Tweets until there is no longer a next_token available. Some libraries and third-party tools may have pagination built-in.

In the process of shaping your data, you may need to take an iterative approach to adjust your query until it returns a payload that meets your objective. Sometimes using a REST client such as Postman or Insomnia can be helpful for seeing what data you get back and making adjustments before you start writing code. Our Postman collection may also be helpful.

Step 4: Build any additional logic or connect to other APIs you are using

After you have a payload that contains exactly what you are looking for you can now make sure your code has built-in logic, timing, or API connections needed to perform the task you identified in your objective. 

For the example of creating a workflow trigger for when TwitterDev Tweets the words “important” and “change”, you will need to see if those two words appear in the text of the Tweet and connect to an API or library to send an email to your work account that contains the text of the Tweet when those two words appear. You will also need to set up a time for this action to happen regularly such as using a Cron Job or AWS Lambda. For this example, you may want to do this on a weekly basis to see if any Tweets from this past week mentioned those two words. We have a similar code sample which looks to see if the words “suspended” and “tomorrow” appear in the same Tweet by the handle @NYCASP and sends you a text.

With the example of performing sentiment analysis on your Tweets from the past week, you will need to create your own logic for using a library such as TensorFlow or connect to a sentiment analysis API. From there, you may want to create a data visualization of your Tweet sentiment from the past week to determine how positive of a week it was. You can check out a blog post walking you through how to create this sample step by step or take a look at the code.

from Tumblr https://generouspiratequeen.tumblr.com/post/627884529041997824

Boost Page Speed By Using Only A CSS Property!

Boost Page Speed By Using Only A CSS Property!:

 

https://damianfallon.blogspot.com/

Google just released Chrome 85, the major update for this browser in 2020. Just like those previous major updates, Chrome got a bunch of fixes and new features. Which includes content-visibility: auto also.

When we develop a site or page for a browser, it requires several steps to render or to show the page to the users. Browser goes through multiple processes before even it paint its first pixel of our site. After that it does these process for the whole page including the contents or elements that is not visible or not in the viewport yet.

After publishing of Chrome 85, developers now can easily make this process shorter by using content-visibility: auto to an element. This CSS property tells the browser that specific element can be skipped until it has been scrolled to the viewport.

#element {
    content-visibility: auto;
}

I have already applied it to one my project and the performance boosted impressively than earlier. Previously the Lighthouse speed was 66. But after applying content-visibility: auto to the elements that will be scrolled later, made the performance speed to 83. Which is amazing!

So start using it now and discuss your experience in the comments section.

https://damianfallon.blogspot.com/

from Tumblr https://generouspiratequeen.tumblr.com/post/627884528705355776

12 Best Google Design & Development Tools

12 Best Google Design & Development Tools:

https://damianfallon.blogspot.com/
Google resembles an iceberg: there’s the part above the water we can see and use everyday; there’s also the part beneath the water, that we don’t see and know little about.

While many of us are concerned about the aspects of Google we don’t see — the parts that threaten our privacy, or monopolize the web — there’s no denying that Google offers some amazing products and tools, many of them free, all from the convenience of a single login.

Today we’re going to take a look at 12 tools from Google that really do bring something positive to the table.

1. Polymer

Polymer is an open-source JavaScript library from Google for building web applications using Web Components. The platform comes with a ton of libraries and tools to help designers and developers unlock the web’s potential by taking advantage of features like HTTP/2, Web Components, and Service Workers. 

The main feature of Polymer is Web Components. With Web Components, you can share custom elements to any site, work seamlessly with any browser’s built-in elements, and effectively use frameworks of all kinds. Products like LitElement (a simple base class for creating fast, lightweight web components) and PWA Starter Kit make Polymer easy to use. If you like, you can build your app entirely out of Web Components. 

2. Lighthouse

Google Lighthouse is an open-source, automated tool for improving the quality of web pages. The software allows you to audit web pages for performance, SEO, accessibility, and more. You can run Lighthouse using ChromeDevTools, directly from the command line, or as a Node module. 

To use Lighthouse in Google Chrome, just go to the URL you want to audit (you can audit any URL on the web), open ChromeDevTools, and click the Audits tab. After you have run the audit, Lighthouse will give you an in-depth report on the web page. 

With these reports, you will see which parts of your web page you need to optimize. Each report has a reference doc that explains why that audit is important and also shows you the steps you can take to fix it. 

You can also use Lighthouse CL to prevent regression on your sites. Using Lighthouse Viewer, you can view and share reports online. You can also share reports as JSON or GitHub Gists. 

Lighthouse also comes with a feature called Stack Packs that allows Lighthouse to detect what platform a site is built on. It also displays specific stack-based recommendations.

3. Flutter

Flutter is Google’s UI toolkit for building natively compiled applications for mobile, web, and desktop from a single codebase. The toolkit is open source and free to use. The best part of Flutter is that it works with existing code. 

The toolkit has a layered architecture that allows for full customization, which results in fast rendering and flexible designs. It also comes with fully-customizable widgets that allow you to build native interfaces in minutes. With these widgets, you will be able to add platform features such as scrolling, navigation, icons, and fonts to provide a full native performance on both iOS and Android.

Flutter also has a feature called hot reload that allows you to easily build UIs, add new features, and fix bugs faster. You can also compile Flutter code to native ARM machine code using Dart native compilers. 

4. Google GitHub

Google GitHub is a software development platform that allows millions of developers to host and review code, manage projects, and build software together. Google GitHub is an open-source platform and has 1791 repositories. 

GitHub allows for easy collaboration among developers. GitHub for teams makes it easy for teams to work through problems, share the weight of the software they are trying to build, and learn from each other along the way. GitHub also allows Project managers and developers to coordinate, track, and update their work in one place. There is also a GitHub Marketplace where you can discover new tools for every step of your development process.

5. Google API Explorer

Google has a huge library of APIs that are available to developers but finding these APIs can be difficult. Google API Explorer makes it easy for developers to locate any API. On the Google API Explorer web page, you will see a complete list of the entire API library. You can easily scroll through the list or use the search box to filter through the API list. 

The best part of Google API Explorer is that each link to a reference page comes with more details on how to use the API. API Explorer is an excellent way to try out methods in the Monitoring API without having to write any code.

6. Puppeteer

Puppeteer is a project from the Google Chrome team. The platform enables web developers to control a Chrome (or any other Chrome DevTools Protocol based browser) and execute common actions, much like in a real browser. Puppeteer is also a Node library and it provides a high-level API for working with headless Chrome. It is also a useful tool for scraping, testing, and automating web pages. 

Here are some things you can do with Puppeteer: generate screenshots and PDFs of pages, UI testing, test Chrome Extensions, automate form submission, generate pre-rendered content, and crawl Single-Page Applications. 

7. Codelabs

Google Developer Codelabs is a handy tool for beginner developers and even advanced developers who want to improve their knowledge. Codelabs provide a guided, tutorial, hands-on coding experience. Codelabs’ site is broken down into several tutorial sessions on different topics. 

With the tutorials on Codelabs, you can learn how to build applications from scratch. Some of the tutorial categories include Augmented reality, TensorFlow, Analytics, Virtual Analytics, G Suite, Search, Google Compute Engine, and Google APIs on iOS. 

8. Color Tool

Color Tool makes it easy for web designers to create, share, and apply colors to their UI. It also measures the accessibility level for any color combination before exporting to the palette. The tool comes with 6 user interfaces and offers over 250 colors to choose from. 

The tool is also very easy to use. All you need to do is pick a color and apply it to the primary color scheme; switch to the secondary color scheme, and pick another color. You can also switch to Custom to pick your own colors. After you have selected all your colors, use the Accessibility feature to check if all is good before exporting it to your palette. 

9. Workbox

Workbox is a set of JavaScript libraries and Node modules. The JavaScript libraries make it easy to add offline support to web apps. The Node modules make it easy to cache assets and offer other features to help users build Progressive Web Apps. Some of these features include pre-caching, runtime caching, request routing, background sync, debugging, and greater flexibility than sw-precache and sw-toolbox. 

With Workbox, you can add a quick rule that enables you to cache Google fonts, images, JavaScript, and CSS files. Caching these files will make your web page to run faster and also consume less storage. You can also pre-cache your files in your web app using their CLI, Node module, or webpack plugin. 

10. PageSpeed Insights

PageSpeed Insights is a handy tool from Google Developers that analyzes the content of a web page, then generates suggestions on how to make the page faster. It gives reports on the performance of a web page on both desktop and mobile devices. At the top of the report, PageSpeed Insights provides a score that summarizes the page’s performance. 

11. AMP On Google

AMP pages load faster and also look better than standard HTML pages on mobile devices. AMP on Google allows you to enhance your AMP pages across Google. It is a web component framework that allows you to create user-first websites, ads, emails, and stories. One benefit of AMP is that it allows your web pages to load almost instantly across all devices and platforms hence improving the user’s experience. 

12. Window Resizer

When creating websites, it is important that developers test them for responsive design – this is where Google’s Window Resizer comes in. Window Resizer is a Chrome extension that resizes the browser window so that you can test your responsive design on different screen resolutions. The common screen sizes offered are desktop, laptop, and mobile, but you can also add custom screen sizes. 

https://damianfallon.blogspot.com/

from Tumblr https://generouspiratequeen.tumblr.com/post/627725988941463552

15 Awesome Developer Home Workstations

15 Awesome Developer Home Workstations:

1. The “Couples Who Code” workstation


Made by digi928

2. The “B&W” workstation


Made by Berlony

3. The “Work Hard Play Hard” workstation


Made by Diamonddog4

4. The “Neck Pain” workstation


Made by EkkoJun

5. The “Bookworm” workstation


Made by v1dal

6. The “Self-Surveillance” workstation


Made by Warat Wongmaneekit

7. The “Visionary” workstation


Made by ChicagoProper

8. The “Nature Boy” workstation


Made by EvanBarbour

9. The “Practical Dev” workstation


Made by ncktyler

10. The “Productivity God” workstation


Made by sukisogreat

11. The “Ambient Light” workstation


Made by flobernd

12. The “Xbox-First” workstation


Made by mburn14

13. The “there’s gotta be something wrong with that guy’s” workstation


Made by Browsingredditnow

14. The “keep it simple” workstation


Made by Jokosmash

15. The “Not enough screen space” workstation

https://damianfallon.blogspot.com/

from Tumblr https://generouspiratequeen.tumblr.com/post/627725988619501568

FastAPI for Flask Users

FastAPI for Flask Users:

 

https://damianfallon.blogspot.com/

I recently decided to give FastAPI a spin by porting a production Flask project. It was very easy to pick up FastAPI coming from Flask and I was able to get things up and running in just a few hours.

The added benefit of automatic data validation, documentation generation and baked-in best-practices such as pydantic schemas and python typing makes this a strong choice for future projects.

In this post, I will introduce FastAPI by contrasting the implementation of various common use-cases in both Flask and FastAPI.

Version Info:

At the time of this writing, the Flask version is 1.1.2 and the FastAPI version is 0.58.1

Installation

Both Flask and FastAPI are available on PyPI. For conda, you need to use the conda-forge channel to install FastAPI while it’s available in the default channel for Flask.

Flask:

pip install flask
conda install flask

FastAPI:

pip install fastapi uvicorn
conda install fastapi uvicorn -c conda-forge

Running “Hello World”

Flask:

# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return {'hello': 'world'}

if __name__ == '__main__':
    app.run()

Now you can run the development server using the below command. It runs on port 5000 by default.

python app.py

FastAPI

# app.py
import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def home():
    return {'hello': 'world'}

if __name__ == '__main__':
    uvicorn.run(app)

FastAPI defers serving to a production-ready server called uvicorn. We can run it in development mode with a default port of 8000.

python app.py

Production server

Flask:

# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return {'hello': 'world'}

if __name__ == '__main__':
    app.run()

For a production server, gunicorn is a common choice in Flask.

gunicorn app:app

FastAPI

# app.py
import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def home():
    return {'hello': 'world'}

if __name__ == '__main__':
    uvicorn.run(app)

FastAPI defers serving to a production-ready server called uvicorn. We can start the server as:

uvicorn app:app

You can also start it in hot-reload mode by running

uvicorn app:app --reload

Furthermore, you can change the port as well.

uvicorn app:app --port 5000

The number of workers can be controlled as well.

uvicorn app:app --workers 2

You can use gunicorn to manage uvicorn as well using the following command. All regular gunicorn flags such as number of workers(-w) work.

gunicorn -k uvicorn.workers.UvicornWorker app:app

HTTP Methods

Flask:

@app.route('/', methods=['POST'])
def example():
    ...

FastAPI:

@app.post('/')
def example():
    ...

You have individual decorator methods for each HTTP method.

@app.get('/')
@app.put('/')
@app.patch('/')
@app.delete('/')

URL Variables

We want to get the user id from the URL e.g. /users/1 and then return the user id to the user.

Flask:

@app.route('/users/')
def get_user_details(user_id):
    return {'user_id': user_id}

FastAPI:

In FastAPI, we make use of type hints in Python to specify all the data types. For example, here we specify that user_id should be an integer. The variable in the URL path is also specified similar to f-strings.

@app.get('/users/{user_id}')
def get_user_details(user_id: int):
    return {'user_id': user_id}

Query Strings

We want to allow the user to specify a search term by using a query string ?q=abcin the URL.

Flask:

from flask import request

@app.route('/search')
def search():
    query = request.args.get('q')
    return {'query': query}

FastAPI:

@app.get('/search')
def search(q: str):
    return {'query': q}

JSON POST Request

Let’s take a toy example where we want to send a JSON POST request with a textkey and get back a lowercased version.

# Request
{"text": "HELLO"}
# Response
{"text": "hello"}

Flask:

from flask import request

@app.route('/lowercase', methods=['POST'])
def lower_case():
    text = request.json.get('text')
    return {'text': text.lower()}

FastAPI:

If you simply replicate the functionality from Flask, you can do it as follows in FastAPI.

from typing import Dict

@app.post('/lowercase')
def lower_case(json_data: Dict):
    text = json_data.get('text')
    return {'text': text.lower()}

But, this is where FastAPI introduces a new concept of creating Pydantic schema that maps to the JSON data being received. We can refactor the above example using pydantic as:

from pydantic import BaseModel

class Sentence(BaseModel):
    text: str

@app.post('/lowercase')
def lower_case(sentence: Sentence):
    return {'text': sentence.text.lower()}

As seen, instead of getting a dictionary, the JSON data is converted into an object of the schema Sentence. As such, we can access the data using data attributes such as sentence.text. This also provides automatic validation of data types. If the user tries to send any data other than a string, they will be given an auto-generated validation error.

Example Invalid Request

{"text": null}

Automatic Response

{
"detail": [
{
"loc": [
"body",
"text"
],
"msg": "none is not an allowed value",
"type": "type_error.none.not_allowed"
}
]
}

File Upload

Let’s create an API to return the uploaded file name. The key used when uploading the file will be file.

Flask

Flask allows accessing the uploaded file via the request object.

# app.py

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files.get('file')
    return {'name': file.filename}

FastAPI:

FastAPI uses function parameter to specify the file key.

# app.py
from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post('/upload')
def upload_file(file: UploadFile = File(...)):
    return {'name': file.filename}

Form Submission

We want to access a text form field that’s defined as shown below and echo the value.


Flask

Flask allows accessing the form fields via the request object.

# app.py

from flask import Flask, request
app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def echo():
    city = request.form.get('city')
    return {'city': city}

FastAPI:

We use function parameter to define the key and data type for the form field.

# app.py
from fastapi import FastAPI, Form
app = FastAPI()

@app.post('/submit')
def echo(city: str = Form(...)):
    return {'city': city}

We can also make the form field optional as shown below

from typing import Optional

@app.post('/submit')
def echo(city: Optional[str] = Form(None)):
    return {'city': city}

Similarly, we can set a default value for the form field as shown below.

@app.post('/submit')
def echo(city: Optional[str] = Form('Paris')):
    return {'city': city}

Cookies

We want to access a cookie called name from the request.

Flask

Flask allows accessing the cookies via the request object.

# app.py

from flask import Flask, request
app = Flask(__name__)

@app.route('/profile')
def profile():
    name = request.cookies.get('name')
    return {'name': name}

FastAPI:

We use parameter to define the key for the cookie.

# app.py
from fastapi import FastAPI, Cookie
app = FastAPI()

@app.get('/profile')
def profile(name = Cookie(None)):
    return {'name': name}

Modular Views

We want to decompose the views from a single app.py into separate files.

- app.py
- views
- user.py

Flask:

In Flask, we use a concept called blueprints to manage this. We would first create a blueprint for the user view as:

# views/user.py
from flask import Blueprint
user_blueprint = Blueprint('user', __name__)

@user_blueprint.route('/users')
def list_users():
    return {'users': ['a', 'b', 'c']}

Then, this view is registered in the main app.py file.

# app.py
from flask import Flask
from views.user import user_blueprint

app = Flask(__name__)
app.register_blueprint(user_blueprint)

FastAPI:

In FastAPI, the equivalent of a blueprint is called a router. First, we create a user router as:

# routers/user.py
from fastapi import APIRouter
router = APIRouter()

@router.get('/users')
def list_users():
    return {'users': ['a', 'b', 'c']}

Then, we attach this router to the main app object as:

# app.py
from fastapi import FastAPI
from routers import user

app = FastAPI()
app.include_router(user.router)

Data Validation

Flask

Flask doesn’t provide any input data validation feature out-of-the-box. It’s common practice to either write custom validation logic or use libraries such as marshmalllow or pydantic.

FastAPI:

FastAPI wraps pydantic into its framework and allow data validation by simply using a combination of pydantic schema and python type hints.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    name: str
    age: int

@app.post('/users')
def save_user(user: User):
    return {'name': user.name,
            'age': user.age}

This code will perform automatic validation to ensure name is a string and age is an integer. If any other data type is sent, it auto-generates validation error with a relevant message.

Here are some examples of pydantic schema for common use-cases.

Example 1: Key-value pairs

{
"name": "Isaac",
"age": 60
}
from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

Example 2: Collection of things

{
"series": ["GOT", "Dark", "Mr. Robot"]
}
from pydantic import BaseModel
from typing import List

class Metadata(BaseModel):
    series: List[str]

Example 3: Nested Objects

{
"users": [
{
"name": "xyz",
"age": 25
},
{
"name": "abc",
"age": 30
}
],
"group": "Group A"
}
from pydantic import BaseModel
from typing import List

class User(BaseModel):
    name: str
    age: int

class UserGroup(BaseModel):
    users: List[User]
    group: str

You can learn more about Python Type hints from here.

Automatic Documentation

Flask

Flask doesn’t provide any built-in feature for documentation generation. There are extensions such as flask-swagger or flask-restful to fill that gap but the workflow is comparatively complex.

FastAPI:

FastAPI automatically generates an interactive swagger documentation endpoint at /docs and a reference documentation at /redoc.

For example, say we had a simple view given below that echoes what the user searched for.

# app.py
from fastapi import FastAPI

app = FastAPI()

@app.get('/search')
def search(q: str):
    return {'query': q}

Swagger Documentation

If you run the server and goto the endpoint http://127.0.0.1:8000/docs, you will get an auto-generated swagger documentation.

You can interactively try out the API from the browser itself.

ReDoc Documentation

In addition to swagger, if you goto the endpoint http://127.0.0.01:8000/redoc, you will get an auto-generated reference documentation. There is information on parameters, request format, response format and status codes.

Cross-Origin Resource Sharing(CORS)

Flask

Flask doesn’t provide CORS support out of the box. We need to use extension such as flask-cors to configure CORS as shown below.

# app.py

from flask import Flask
from flask_cors import CORS

app_ = Flask(__name__)
CORS(app_)

FastAPI:

FastAPI provides a built-in middleware to handle CORS. We show an example of CORS below where we are allowing any origin to access our APIs.

# app.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Conclusion

Thus, FastAPI is an excellent alternative to Flask for building robust APIs with best-practices baked in. You can refer to the documentation to learn more.

from Tumblr https://generouspiratequeen.tumblr.com/post/627725987930685440

The Most Trending CSS Frameworks Analogy 2020

The Most Trending CSS Frameworks Analogy 2020:

 

CSS Frameworks Comparison

FEEL FREE TO SHARE THIS IMAGE ON YOUR SITE/BLOG WITH ATTRIBUTION 😀

1.Bootstrap: World’s Most Popular Framework

Bootstrap is the world’s best CSS framework with large community support. This framework is built in HTML, SASS, and javascript. Currently, Bootstrap 4.5.0 is the latest version with more responsiveness with utility classes and new components. It is directed at the responsive, mobile-first front end development which makes it usable for any device and developer-friendly. Bootstrap supports all modern browsers.

This is originally developed by twitter which is the main reason behind the popularity of this framework and more powerful documents. The best advantage of bootstrap is, this framework has great javascript components with custom files or CDN. Bootstrap admin templates are widely used for web apps because of its responsiveness.

If you are looking for a best Free bootstrap admin template then have a look at Chameleon lite. It is a Modern Bootstrap 4 WebApp & Admin Dashboard Html Template elegant design, clean and organized code

Bootstrap 5 is the upcoming version. For more info, Visit Bootstrap 5 Release date, Important updates, and Latest Tutorial

*Reasons to use Bootstrap:*

  • Bootstrap offers lots of examples and pre-set layout to get you started with.
  • With Bootstrap, the developers can easily stitch different components together and layouts to create a new and impressive page design.
  • Many detailed documentations are provided with those layouts so that the users can understand them easily.
  • Bootstrap is based on the MIT License, therefore it is free to use, free to distribute, so you can develop and you can contribute to the community as well.
  • Bootstrap’s Github page GitHub consists of more than 19,000 commits and 1,100 contributors.

Some additional Info:

  • Release date: August 19, 2011
  • Current Version: 4.5.0
  • Git star, Forks, Contributors: 141k, 68.7k, 1115
  • Hacker News, Reddit, Stack overflow: 3.3k, 9k, 98k
  • License: MIT
  • No. of sites: 20,737,671
  • Documentation: Excellent
  • Customization: Basic GUI Customizer (need to put color values manually)
  • Core concept: RWD and mobile-first
  • Learning Curve: Mild
  • Grid: Flexbox-based up to 12 column
  • Size: Minified CSS: 58.6KB. Gzip: 15.6KB
  • Browser Support: Latest Chrome, Safari, Firefox, Opera, Safari, Edge & IE 10+, Android v5.0+
  • Companies usingSpotifyCourseraVineTwitterWalmart and Many more

Pros:

  • Responsiveness
  • Consistent & Flexible
  • HTML, CSS, and JS framework
  • Customizable
  • Large Community
  • Excellent Documentation

Cons:

  • Javascript is tied to Jquery

Ideal for:

  • A beginner who is new to CSS, as he or she can kick start Bootstrap without any hurdles.
  • A developer with little knowledge of JavaScript who can still use Bootstrap components without writing a line in JS.
  • A back-end developer who wants to make some UI changes even if he or she is new to both HTML and CSS.

2.Bulma: Free, Open Source CSS Framework

Bulma is a responsive modern CSS framework. This framework is built-in HTML, SASS CSS prospector, and CSS flexbox. Bulma gives lots of options to customize with your requirements using sass files, web packs, and variables. Bulma is created in pure CSS., which means while using the framework all you need is one .css file and no .js.

This framework offers plenty of options to customize with your requirements using web packs, sass files, and variables.

This framework has some highly advanced features which help you to make your website more attractive and less code’s. You can use the utility’s functions to create dark and light color patterns. It has the same grids as bootstrap. Bulma allows you to add SASS Modularity. It is compatible with both Font Awesome 4 and Font Awesome 5 thanks to the .icon element.

Bulma is easy to learn. It is well documented.

Reasons to use Bulma:

  • Bulma offers clean and simple presets which make it easy to choose as per the topics the developer wants to explore.
  • Bulma provides a decent number of web components from which, one can just simply choose and use it to design as per requirements and modification.
  • Bulma’s GitHub page has more than, 400 commits and 300 contributors.

Some additional Info:

  • Release date: January 24, 2016
  • Current Version: 0.8.2
  • Git star, Forks, Contributors: 39.6k, 3.4k, 302
  • Reddit, Stack overflow: 1.2k, 581
  • License: MIT
  • No. of sites: 30,987
  • Documentation: Good
  • Customization: Basic GUI Customizer
  • Core concept: RWD, mobile-first, Modern free
  • Grid: Simple building of column layout
  • Size: Minified CSS: 73kb. Gzip: 10kb
  • Browser Support: Latest Chrome, Edge, Firefox, Opera, Safari, IE 10+ (Partially supported)
  • Companies using: Dev TubeEconomistRubrik, and many more

Pros:

  • Lightweight
  • Easy to Use
  • Responsive Design
  • Based on Flexbox.
  • Highly customizable and modularizable
  • Simple syntax

Cons:

  • Community support is limited
  • Less documentation
  • Less flexibility
  • Limited browser support.

Ideal For:

  • From beginner to pro, any developer can use it due to its simplicity.

3. Foundation: The Most Advanced Front-end Framework

Foundation is an advanced frontend CSS framework, built-in HTML, CSS, SASS, and javascript. This framework has a sass compiler with a faster way to design a website. Foundation has its own CLI to install in your pc/Laptop using specific commands and you can easily watch. Similar same file structure like bootstrap Bulma and materialize CSS. This is a mobile-first approach CSS framework with fully responsive with components.

Plenty of forums are available for supports and help to fix any type of issue quickly. Mostly this framework is used for large web applications, to make an amazing website with a stater template and to design an awesome website with an attractive user-interface.

Foundation is semantic, readable, flexible, and completely customizable. Foundation has comprehensive documentation and video tutorials on an official ZURB Foundation website.

*Reasons to use Foundation:*

  • Foundation is the most advanced CSS framework which allows users to create large web applications and many more.
  • Foundation’s GitHub page shows nearly 1,000 contributors and 17,000 commits.
  • It is modular and consists mainly of Sass style sheets.
  • It is updated constantly to support the newest features such as grids with flexbox support.

Some additional Info:

  • Release date: November 4, 2014
  • Current Version: 1.0.0
  • Git star, Forks, Contributors: 28.6k, 5.8k, 982
  • Reddit, Stack overflow: 1.2k, 803
  • License: MIT
  • No. of sites: 441,292
  • Documentation: Good
  • Customization: Advance GUI Customizer(for the previous version)
  • Core concept: RWD and mobile-first
  • Grid: Standard 12 column fluid responsive grid system
  • Size: Minified CSS: 30kb. Gzip: 7kb
  • Browser Support: Last Two Versions of Chrome, Firefox, Safari, Opera, Mobile Safari, IE Mobile, Edge and IE 9+, Android Browser 4.4+
  • Companies usingAmazonHpAdobeMozillaEADisney and many more

Pros:

  • Device agnostic
  • Responsive
  • Easy to use
  • Modern Look
  • Customizable
  • Good Documentation

Cons:

  • Limited browser support
  • Heavy/large

*Ideal For:

*

  • Professional, highly skilled developers and designers whose aim is to create a unique website and wants to customize the framework.

4. Materialize CSS: A Material Design Based CSS Framework

Materialize CSS is a responsive front-end framework based on the material design with collections of UI-components with minimal effects on which users can easily attract. It is created by Google in 2014. Materialize is fully responsive in Tablets and mobile. You can quickly get started using its starter templates. It is easy to learn as well as excellent documentation is provided.

Materialize Admin Templates based on Materialize CSS framework are vastly used over the world due to its responsiveness.

This framework has large community support and great positive feedback. Materialize CSS allows you to customize options with an impressive set of color collections.

If you are looking for some of the free admin templates/ bootstrap templatesbased on material design. We have handpicked these Material Design Admin templates from various resources on the internet based on usability and Quality.

*Reasons to use Materialize CSS:*

  • The documentation page of Materialize is very comprehensive and pretty easy to start with.
  • Materialize’s GitHub lists more than 3,800 commits and 250 contributors.
  • Materialize’s components page includes cards, buttons, navigation, and many more added features.

Some additional Info:

  • Release date: September 2011
  • Current Version: 6.6.3
  • Git star, Forks, Contributors: 37.5k, 4.8k, 250
  • Reddit, Stack overflow: 374, 3.2k
  • License: MIT
  • No. of sites: 111,481
  • Documentation: Good
  • Customization: Basic GUI Customizer
  • Core concept: RWD,mobile-first, semantic
  • Grid: XY 12- Column grid,Floted (flexbox in latest version)
  • Size: Minified CSS: 90kb. Gzip: 18kb
  • Browser Support: Chrome 35+, Firefox 31+, Safari 9+, Opera, Edge, IE 11+
  • Company Using: Avhana HealthMid DayArchitonic, and many more

Pros:

  • Flexible Grids
  • Offers finest of the customization abilities
  • Possess a robust grid system
  • Supports the rapid development of projects
  • Contains set of templates and readily available codes
  • Offers services for sites as well as emails.
  • JS & jQuery both version available

Cons:

  • Community support is limited
  • Complexity in customization
  • Modification of code is tough

Ideal For:

  • It is accessible to everyone and easy to pick up quickly.

5. UI kit: iOS Specific CSS Framework

UI Kit is a lightweight, modular front-end CSS, and web UI design framework, which offers almost all the major features of other frameworks. UI kits have lots of pre-built components such as Accordion, Alert, Drop, Iconnav, animations, Padding, etc. which shows usage patterns, component options, and methods.

UI kit helps web developers to create clean and modern interfaces. It offers impressive features, especially when it comes to design, there is no competition with UI kit.

Basically, UIKit is the future of developing apps on Apple’s platforms.

Reasons to use UI Kit:

  • It’s one of the most widely used front-end frameworks mainly used for the development of iOS applications. UI Kit defines the core components such as buttons, labels, navigation controllers, and table views
  • UI kit features pre-built components such as Drop, Alert, Accordion, Padding, Iconnav, animations, etc.
  • It helps to develop responsive, powerful, and fast web interfaces. It consists of a comprehensive collection of CSS, HTML, and JS components.
  • UI kit’s GitHub lists more than 3,800 commits and 250 contributors.
  • It is extendable, simple to customize, and easy to use.

Some additional Info:

  • Release date: July 19, 2013
  • Current Version: 3.4.3
  • Git star, Forks, Contributors: 15.7k, 2.2k, 28
  • Hacker News, Reddit, Stack overflow: 139, 21, 8.2k
  • License: MIT
  • No. of sites: 311,897
  • Documentation: Good
  • Customization: Basic GUI Customizer
  • Core concept: Responsive Webdesign, UX focused
  • Grid: Grid, flex and width, the border between grid column
  • Size: Minified CSS: 33kb. Gzip: 6kb
  • Browser Support: Latest Chrome, Firefox, Opera, Edge & Safari 9.1,+ IE 11+
  • Company Using: CrunchyrollLiteTubeRover.com and many more

Pros:

  • Complete GUI
  • Easy modification
  • Simple
  • Easy to learn
  • Light Weight
  • Well-Architected

Cons:

  • Slow development
  • Messy code class
  • Closed development
  • Community support is limited

Ideal For:

  • Professional and highly experienced developers because of the lack of available learning resources.
CONCLUSION:-

The above-detailed analogy of the trending CSS framework gives a comprehensive overview of the most used and recommended frameworks of 2020. Each framework offers unique features and lots of components which makes them preferable for your web apps. You will definitely find this detailed analogy useful and noteworthy, as we have covered all the major aspects of the CSS framework that you might be looking for.

Although the selection of a framework depends on the following parameters:

  • What sort of CSS pre-processor do you need?
  • License
  • UI design preference.
  • Grid system
  • Responsiveness
  • Community support
  • Browser support

So after prioritizing parameters as listed above, you’ll find it very easy to choose the right CSS framework by using this CSS framework infographic and article.

For example, if you are trying to make a lightweight site that will work fast or a design-oriented website, then you should go for a lightweight framework like Bootstrap. If you are working on a Material Design-oriented project, then you should choose the Materialize CSS framework.

Experienced developers 😎 advise not to stick to one and the only framework, instead use several of them for the benefit of your website. Apart from that, having a working understanding of multiple frameworks will improvise and build up your skillset, too.

Although, you yourself know what is best for you so in the end what matters is your opinion and selection. So, we hope that you find this article helpful and noteworthy. We have put lots of effort and time to prepare this CSS framework comparison. After going through deep research and digging we have gathered these amazing, responsive, and highly recommended CSS Frameworks suitable for your project.

Do share this with your colleagues, friends, and social media much as you can with attribution. Because sharing is caring…!! Right? 😇

We are sure that after going through this CSS Framework Analogy you’ll be able to choose the right one as per your requirement.

from Tumblr https://generouspiratequeen.tumblr.com/post/627725986836955136

What the heck is Currying anyway?

What the heck is Currying anyway?:

 

https://damianfallon.blogspot.com/

How To Write A Curry Function?

We know how to write a normal function (without currying), for example add()above, which is simple as such.

function add(a, b, c) {
  return a + b + c;
}

console.log(add(1, 2, 3)); // 6

But this is how we write the same function in a curriable manner.

function add(a) {
  return function (b) {
    return function (c) {
      return a + b + c;
    };
  };
}

console.log(add(1)(2)(3)); // 6

If you notice in the curry function, for every passed argument inside add() we are returning one new function which takes another argument and returns another function. And at last, after passing the last argument we return the final result. This is the basic struture of a curry function.

So for add(1) in the curry function, we don’t get a value as a result rather a whole new function which takes (2) as an argument and it goes on until we get a value in output.

Using With Helper Functions

As currying function is not easier to write (always), but being a major concept in functional programming we have many helper functions that help us transform a normal function into a curry function.

These can be done by most JavaScript utility libraries like LodashRambda and so on, with one simple step like this. Also, I’m using lodash in this example.

const _ = require("lodash");

function add(a, b, c) {
  return a + b + c;
}

const curryAdd = _.curry(add);

console.log(add(1, 2, 3)); // 6
console.log(curryAdd(1)(2)(3)); // 6

Creating New Functions From Existing Ones

This is how curry functions are mostly used in real life as it helps us create entire new functions and export them to use it anywhere .

For instance, we are having this array of objects.

const items = [
  { name: "Mango", type: "Fruit" },
  { name: "Tomato", type: "Vegetable" },
  { name: "Strawberry", type: "Fruit" },
  { name: "Potato", type: "Vegetable" },
  { name: "Turnip", type: "Vegetable" },
  { name: "Banana", type: "Fruit" },
  { name: "Carrot", type: "Vegetable" },
];

Now we need to create a function, that returns all items of type Fruits or Vegetables. So, let’s do this using the curry concept that we just learned.

const isType = obj => type => obj.type === type;

const isFruit = item => isType(item)("Fruit");
const isVegetable = item => isType(item)("Vegetable");

const fruits = items.filter(isFruit);
const vegetables = items.filter(isVegetable);

Woah, this looks so clean. But how does this work?

Firstly we are having the isType() as a curry function, which takes in an object and returns a boolean (true/false) after checking it’s type is equal to the passed argument type or not.

But instead of using this function directly, we are creating two more functions that checks for whether type is fruit or vegetable separately. By seeing it’s structure, you’ll notice it just takes one argument which is the current item and calls isType() by passing item and the desired type.

Finally, to get our fruits and vegetables we run a .filter() array method passing either isFruit or isVegetable as a callback function. This by default passes our current item inside items array to the callback. To be more clear, what we’ve done in the end is same as, below.

const fruits = items.filter(item => isFruit(item));
const vegetables = items.filter(item => isVegetable(item));

Results

console.log(fruits)

[
  { name: 'Mango', type: 'Fruit' },
  { name: 'Strawberry', type: 'Fruit' },
  { name: 'Banana', type: 'Fruit' }
]

console.log(vegetables)

[
  { name: 'Tomato', type: 'Vegetable' },
  { name: 'Potato', type: 'Vegetable' },
  { name: 'Turnip', type: 'Vegetable' },
  { name: 'Carrot', type: 'Vegetable' }
]

Ultimately, we came to know how to write a curry function, which was way easier than we thought.

Making Our Own Helper Function

After being able to transform a normal function to a curry function using a helper function, like .curry() from Lodash, I was curious to know how to build one for ourselves. Because, you know at times, we only need handful of functions for which including a giant utility library like Lodash isn’t necessary.

Let’s create a simple usecase first, then we’ll go off to create the actual curry function.

// Assume that curry is a valid function

const multiply = (a, b) => a * b;

const curryMultiply = curry(multiply);

console.log(multiply(2, 4)); // 8
console.log(multiply(2)(4)); // 8

Don’t hit run now, as we yet have to fulfill our assumption and create a valid curry function. And upon running this will definitely give a Reference Error as curry is not defined.

Building the actual curry() function.

function curry(func) {
  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(undefined, args);
    } else {
      return function (...rest) {
        return curried.apply(undefined, rest.concat(args));
      };
    }
  };
}

Firstly, we are creating a function named curry and return another function from it, which is named as curried. As you can see, in the returned function we are checking the number of arguments passed to it, if the number exceeds or is equal to number of arguments the actual function func expects (also called arity) then we return the function by calling apply and passing in all the args.

In case, we got less number of arguments (which happens while we pass parameters one by one) we return another function which stores its arguments in a variable called rest. Finally, we call the same function curried() recursively and pass it the new arguments in rest variable and concat it with previosly gotten arguments in args variable.

Also, if you’re wondering what those 3 dots are (...), they’re a new feature in ES6or ECMAScript2015. They return us all the passed arguments to a function.

Now, if you press enter or run your code you’ll see you get the right output, like this.

console.log(multiply(2, 4)); // 8
console.log(multiply(2)(4)); // 8

You can save this snippet in your Gist or understand it properly, so anytime you just want to use a function with currying instead of writing the function again, you can create a new function altogether by passing old non-curriable function into this curry() method we just created.

Hurray 🎉

If you’re with me yet, then hurray! I hope you learned something new or you could get an edge over fixing hour old bugs. Throw me a tweet at @heytulsiprasadif you find something I missed or just want to say Hi (really that’s becoming important these days). You can expect more blogs on functional programming in coming days.

from Tumblr https://generouspiratequeen.tumblr.com/post/627725986167930880

OOP vs functional programming

OOP vs functional programming:



Introduction

Before we get started with coding I want to give you a quick introduction to object-oriented and functional programming.
Both are programming paradigms differing in the techniques they allow and forbid.
There are programming languages that only support one paradigm e.g. Haskell(purely functional).
Aswell as languages that support multiple paradigms such as JavaScript, you can use JavaScript to write object-oriented or functional code or even a mixture of both.

Setup

Before we can dive deep into the differences between these two paradigms we need to setup the project.
For that we first create all the files and folders we need like this:

$ mkdir func-vs-oop
$ cd ./func-vs-oop
$ cat index.html
$ cat functional.js
$ cat oop.js 

I’m using the cat command because it works both on Linux-systems and Windows Powershell.

Next up we need to create a simple form for the factorial calculator inside the index.html.




  
  http://functional.js


  

Functional vs OOP

Factorial
Calculate

Result:

To give this form a better look and feel we use bootstrap as a CSS-Framework.
If you display this HTML in the browser it should look like this:

Currently this form won’t do anything.
Our goal is to implement a logic where you can enter a number up to 100. After clicking the “Calculate”-button it should show the result in the result-div.
We will implement this both in the object-oriented way and the functional way.

Functional implementation

First off we will create a file for the functional programming approach.

$ cat functional.js

To get started we need a function that get’s called when loading this file into the browser.
This function should get the form and then add the functionality we need to the submit-event of the form.

function addSubmitHandler(tag, handler) {
  const form = getElement(tag);
  form.addEventListener('submit', handler);
}

addSubmitHandler("#factorial-form", factorialHandler);

First we declare the function called addSubmitHandler.
This function takes in two parameters, the first one being the tag we want to look for in our HTML, the second one being the function we want to bind to the submit-event of our Element.

Next we call this function by passing in #factorial-form and the function name factorialHandler.
The hashtag in front of the tag indicates that we are looking for the id-attribute in the HTML.

This code will throw an error if you try to run it now, because neither the function getElement nor factorialHandler are defined anywhere.
So let’s first define getElement above our addSubmitHandler function like this:

function getElement(tag) {
  return document.querySelector(tag);
}

This function is really simple and only returns the HTML-Element we found by the tag we passed in.
But we will reuse this function later on.

Now let’s start creating the core logic by adding the factorialHandler function above the addSubmitHandler.

function factorialHandler(event) {
  event.preventDefault();

  const inputNumber = getValueFromElement('#factorial');

  try {
    const result = calculateFactorial(inputNumber);
    displayResult(result);
  } catch (error) {
    alert(error.message);
  } 
}

We pass in the event and instantly call preventDefault.
This will prevent the default behavior of the submit event, you can try out what happens on the button click without calling preventDefault.

After that we get the value entered by the user from the input-field by calling the getValueFromElement function.
Upon getting the number we try to calculate the factorial by using the function calculateFactorial and then render the result to the page by passing the result to the function displayResult.

If the value is not in the correct format or the number is higher than 100, we will throw an error and display that as and alert.
This is the reason for using a try-catch-block in this particular case.

In the next step we create two more helper functions, getValueFromElement and displayResult.
Let’s add them below the getElement function.

function getValueFromElement(tag) {
  return getElement(tag).value;
}

function displayResult(result) {
  getElement('#factorial-result').innerHTML = result
}

Both of these functions use our getElement function. This reusablility is one part why functional programming is so effective.
To make this even more reusable we could potentially add a second argument to displayResult, called tag.
So that we can dynamically set the element that should display the result.
But in this example I went with the hard-coded way.

Next up we create our calculateFactorial function right above factorialHandler.

function calculateFactorial(number) {
  if (validate(number, REQUIRED) && validate(number, MAX_LENGTH, 100) && validate(number, IS_TYPE, 'number')) {
    return factorial(number);
  } else {
    throw new Error(
      'Invalid input - either the number is to big or it is not a number'
    );
  }
}

We validate if the argument ‘number’ is not empty, not above 100 and of type number.
For that we use a function called validate that we will need to create next.
If the checks pass we call the function factorial and return it’s result.
If these checks don’t pass we throw the error we catched in the factorialHandlerfunction.

First let’s create the validate function right below displayResult and the three constants MAX_LENGTH, IS_TYPE and REQUIRED.

const MAX_LENGTH = 'MAX_LENGTH';
const IS_TYPE = 'IS_TYPE';
const REQUIRED = 'REQUIRED';

function validate(value, flag, compareValue) {
  switch (flag) {
    case REQUIRED:
      return value.trim().length > 0;
    case MAX_LENGTH:
      return value <= compareValue;
    case IS_TYPE:
      if (compareValue === 'number') {
        return !isNaN(value);
      } else if (compareValue === 'string') {
        return isNaN(value);
      }
    default:
      break;
  }
}

In this function we use a switch to determine which kind of validation we are going to perform.
After determining that, it is just a simple value validation.

Now we are going to add the actual factorial function right above the calculateFactorial declaration.
This will be our last function for this approach.

function factorial(number) {
  let returnValue = 1;
  for (let i = 2; i <= number; i++) {
    returnValue = returnValue * i;
  }
  return returnValue;
}

There are many different ways to perform a factorial calculation, I went with the iterative approach.
If you want to learn more about the different approaches I recommend you check out this article on geeksforgeeks:

The final functional.js file should look like this:

const MAX_LENGTH = 'MAX_LENGTH';
const IS_TYPE = 'IS_TYPE';
const REQUIRED = 'REQUIRED';

function getElement(tag) {
  return document.querySelector(tag);
}

function getValueFromElement(tag) {
  return getElement(tag).value;
}

function displayResult(result) {
  getElement('#factorial-result').innerHTML = result
}

function validate(value, flag, compareValue) {
  switch (flag) {
    case REQUIRED:
      return value.trim().length > 0;
    case MAX_LENGTH:
      return value <= compareValue;
    case IS_TYPE:
      if (compareValue === 'number') {
        return !isNaN(value);
      } else if (compareValue === 'string') {
        return isNaN(value);
      }
    default:
      break;
  }
}

function factorial(number) {
  let returnValue = 1;
  for (let i = 2; i <= number; i++) {
    returnValue = returnValue * i;
  }
  return returnValue;
}

function calculateFactorial(number) {
  if (validate(number, REQUIRED) && validate(number, MAX_LENGTH, 100) && validate(number, IS_TYPE, 'number')) {
    return factorial(number);
  } else {
    throw new Error(
      'Invalid input - either the number is to big or it is not a number'
    );
  }
}

function factorialHandler(event) {
  event.preventDefault();

  const inputNumber = getValueFromElement('#factorial');

  try {
    const result = calculateFactorial(inputNumber);
    displayResult(result);
  } catch (error) {
    alert(error.message);
  } 
}

function addSubmitHandler(tag, handler) {
  const form = getElement(tag);
  form.addEventListener('submit', handler);
}

addSubmitHandler("#factorial-form", factorialHandler);

In this approach we worked exclusively with functions. Every function got a single purpose and most of them are reusable in other parts of the application.
For this simple web application the functional approach is a bit of an overkill. Next we will code the same functionality but this time object-oriented.

Object-oriented implementation

First of all we need to change the src in the script-tag of our index.html file to the following.

Now we create the oop.js file.

$ cat oop.js

For the OOP approach we want to create three different classes, one for validation, one for the factorial calculation and one for handling the form.
We get started with creating the class that handles the form.

class InputForm {
  constructor() {
    this.form = document.getElementById('factorial-form');
    this.numberInput = document.getElementById('factorial');

    this.form.addEventListener('submit', this.factorialHandler.bind(this));
  }

  factorialHandler(event) {
    event.preventDefault();

    const number = this.numberInput.value;

    if (!Validator.validate(number, Validator.REQUIRED) 
      || !Validator.validate(number, Validator.MAX_LENGTH, 100)
      || !Validator.validate(number, Validator.IS_TYPE, 'number'))
      {
        alert('Invalid input - either the number is to big or it is not a number');
        return;
      }

      const factorial = new Factorial(number);
      factorial.display();
  }
}

new InputForm();

In the constructor we get the form-element and the input-element and store it in class variables, also called properties.
After that we add the method factorialHandler to the submit-event.
In this case we need to bind ‘this’ of the class to the method.
If we don’t do that we will get reference errors, e.g. calling this.numberInput.valuewill be undefined.
After that we create the class method factorialHandler with the event as an argument.

The code of this method should look somewhat familiar, for example the if-statement checks if the inputvalue is valid or not, like we did in the calculateFactorial function.
Validator.validate is a call to a static method inside the class Validator that we still need to create.
We don’t need to initialize a new instance of an object if we work with static methods.
After the validations pass we create a new instance of the Factorial class, pass in the inputvalue and then display the calculated result to the user.

Next up we are going to create the Validator class right above the InputForm class.

class Validator {
  static MAX_LENGTH = 'MAX_LENGTH';
  static IS_TYPE = 'IS_TYPE';
  static REQUIRED = 'REQUIRED';

  static validate(value, flag, compareValue) {
    switch (flag) {
      case this.REQUIRED:
        return value.trim().length > 0;
      case this.MAX_LENGTH:
        return value <= compareValue;
      case this.IS_TYPE:
        if (compareValue === 'number') {
          return !isNaN(value);
        } else if (compareValue === 'string') {
          return isNaN(value);
        }
      default:
        break;
    }
  }
}

As you can see everything inside of this class is static, the method validate aswell as the three properties.
Therefor we do not need any constructor.
The advantage of this is that we do not need to initialize this class everytime we want to use it.
validate is mostly the same as the validate function is our functional.js except that we do this.REQUIREDthis.MAX_LENGTH and this.IS_TYPE instead of just the variable name.

Next up we create our Factorial class right below the Validator class.

class Factorial {
  constructor(number) {
    this.resultElement = document.getElementById('factorial-result');
    this.number = number;
    this.factorial = this.calculate();
  }

  calculate() {
    let returnValue = 1;
    for (let i = 2; i <= this.number; i++) {
      returnValue = returnValue * i;
    }
    return returnValue;
  }

  display() {
    this.resultElement.innerHTML = this.factorial;
  }
}

Upon initializing an instance of this class we get the resultelement and store it as a property aswell as the number we pass in.
After that we call the method calculate and store it’s return value in a property.
The calculate method contains the same code as the factorial function in functional.js.
Last but not least we got the display method that sets the innerHTML of our resultelement to the calculated factorial number.

The complete oop.js file should look like this.

class Validator {
  static MAX_LENGTH = 'MAX_LENGTH';
  static IS_TYPE = 'IS_TYPE';
  static REQUIRED = 'REQUIRED';

  static validate(value, flag, compareValue) {
    switch (flag) {
      case this.REQUIRED:
        return value.trim().length > 0;
      case this.MAX_LENGTH:
        return value <= compareValue;
      case this.IS_TYPE:
        if (compareValue === 'number') {
          return !isNaN(value);
        } else if (compareValue === 'string') {
          return isNaN(value);
        }
      default:
        break;
    }
  }
}

class Factorial {
  constructor(number) {
    this.resultElement = document.getElementById('factorial-result');
    this.number = number;
    this.factorial = this.calculate();
  }

  calculate() {
    let returnValue = 1;
    for (let i = 2; i <= this.number; i++) {
      returnValue = returnValue * i;
    }
    return returnValue;
  }

  display() {
    this.resultElement.innerHTML = this.factorial;
  }
}

class InputForm {
  constructor() {
    this.form = document.getElementById('factorial-form');
    this.numberInput = document.getElementById('factorial');

    this.form.addEventListener('submit', this.factorialHandler.bind(this));
  }

  factorialHandler(event) {
    event.preventDefault();

    const number = this.numberInput.value;

    if (!Validator.validate(number, Validator.REQUIRED) 
      || !Validator.validate(number, Validator.MAX_LENGTH, 100)
      || !Validator.validate(number, Validator.IS_TYPE, 'number'))
      {
        alert('Invalid input - either the number is to big or it is not a number');
        return;
      }

      const factorial = new Factorial(number);
      factorial.display();
  }
}

new InputForm();

We created three different classes handling three different aspects of our application:

  • Validation: Validation class
  • Factorial Handling: Factorial class
  • Form Handling: InputForm class

Conclusion

Both approaches are valid ways of structuring your code.
Personally I like to try out what works best in the different projects I work on.
Most of the time it is not even possible to seperate both paradigms so clearly.
I hope this little comparison gave you a fundamental understanding of what the different approaches look like.

from Tumblr https://generouspiratequeen.tumblr.com/post/627714667311202304