JavaScript is one of the most popular programming languages out there, and as most people say, “If you want to learn a programming language, learn JavaScript.”

Quincy Larson, founder of FreeCodeCamp, was asked in a recent interview which language developers should learn first. He replied, “JavaScript.” :

“Software is eating the world, JavaScript is eating software. JavaScript is becoming more and more dominant every year, and no one knows what will eventually replace it.” If you don’t have a good reason to learn a new language (for example, your job requires you to maintain a non-javascript code base), my advice is to focus on improving JavaScript.”

You must be excited to hear all this. Here are 127 common JS code snippets for you to learn and use.

1, all

Returns true if all elements of the array satisfy the function condition. When called, if the second argument is omitted, a Boolean value is passed by default.

const all = (arr, fn = Boolean) = > arr.every(fn);

all([4.2.3], x => x > 1); // true
all([1.2.3]); // trueCopy the code

2, allEqual

Determines whether the elements in the array are all equal

const allEqual = arr= > arr.every(val= > val === arr[0]);

allEqual([1.2.3.4.5.6]); // false
allEqual([1.1.1.1]); // trueCopy the code

3, approximatelyEqual

This code example checks if two numbers are approximately equal, and the difference can be set by passing a parameter

const approximatelyEqual = (v1, v2, epsilon = 0.001) = > Math.abs(v1 - v2) < epsilon;

approximatelyEqual(Math.PI / 2.0.1.5708); // trueCopy the code

4, arrayToCSV

This code converts elements without commas or double quotes to comma-delimited strings recognized by CSV format.

const arrayToCSV = (arr, delimiter = ', ') = >
  arr.map(v= > v.map(x= > `"${x}"`).join(delimiter)).join('\n');
  
arrayToCSV([['a'.'b'], ['c'.'d']]); // '"a","b"\n"c","d"'
arrayToCSV([['a'.'b'], ['c'.'d']], '; '); // '"a";" b"\n"c";" d"'Copy the code

5, arrayToHtmlList

This code converts the array element to a <li> tag and adds the element to the given ID element tag.

const arrayToHtmlList = (arr, listID) = >
  (el= > (
    (el = document.querySelector(The '#' + listID)),
    (el.innerHTML += arr.map(item= > `<li>${item}</li>`).join(' '())))); arrayToHtmlList(['item 1'.'item 2'].'myListID');Copy the code

6, attempt

This code executes a function that passes the remaining arguments back to the function as arguments, returns the corresponding results, and can catch exceptions.

const attempt = (fn, ... args) = > {
  try {
    returnfn(... args); }catch (e) {
    return e instanceof Error ? e : new Error(e); }};var elements = attempt(function(selector) {
  return document.querySelectorAll(selector);
}, '> _ >');
if (elements instanceof Error) elements = []; // elements = []Copy the code

7, business,

This code returns the average of two or more numbers.

const average = (. nums) = > nums.reduce((acc, val) = > acc + val, 0) / nums.length; average(... [1.2.3]); / / 2
average(1.2.3); / / 2Copy the code

8 averageBy.

An example of a combination of map() and reduce() functions that convert objects to arrays using map() and then add them up by calling Reduce (), and then return the average based on the array length.

const averageBy = (arr, fn) = >
  arr.map(typeof fn === 'function' ? fn : val= > val[fn]).reduce((acc, val) = > acc + val, 0) /
  arr.length;
  
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); / / 5
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6}].'n'); / / 5Copy the code

9, bifurcate,

This function takes two arguments, both of type array, and groups the arrays of one argument based on the condition that the second argument is true in the first array and the others in the second array. Array.prototype.reduce() and array.prototype.push () are used here.

const bifurcate = (arr, filter) = >
  arr.reduce((acc, val, i) = > (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
bifurcate(['beep'.'boop'.'foo'.'bar'], [true.true.false.true]); 
// [ ['beep', 'boop', 'bar'], ['foo'] ]Copy the code

10, bifurcateBy

This code groups arrays according to the specified function logic. If the logic that meets the function condition is true, it is placed in the first array. If the logic that does not meet the function condition, it is placed in the second array. Array.prototype.reduce() and array.prototype.push () are used to add them to the Array using array.prototype.push (), based on function filtering logic.

const bifurcateBy = (arr, fn) = >
  arr.reduce((acc, val, i) = > (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
  
bifurcateBy(['beep'.'boop'.'foo'.'bar'], x => x[0= = ='b'); 
// [ ['beep', 'boop', 'bar'], ['foo'] ]Copy the code

11, bottomVisible

Used to check whether the page scrolls to the bottom of the page.

const bottomVisible = (a)= >
  document.documentElement.clientHeight + window.scrollY >=
  (document.documentElement.scrollHeight || document.documentElement.clientHeight);

bottomVisible(); // trueCopy the code

12, byteSize

This code returns the length of the string in bytes. The Blob Object is used here. A Blob (Binary Large Object) Object represents a piece of Binary data and provides a series of interfaces for manipulation. Other apis for manipulating binary data, such as File objects, are built on top of Blob objects, inheriting their properties and methods. There are two ways to generate Blob objects: either by using the Blob constructor, or by slicing out a portion of an existing Blob object using the slice method.

const byteSize = str= > new Blob([str]).size;

byteSize('😀'); / / 4
byteSize('Hello World'); / / 11Copy the code

13 and capitalize

Convert the first letter of a string to uppercase, which is mainly used in the application of ES6 expansion syntax in the array.

const capitalize = ([first, ...rest]) = >
  first.toUpperCase() + rest.join(' ');
  
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar'.true); // 'FooBar'Copy the code

14, capitalizeEveryWord

Convert the first letter of each word in a sentence to a capital letter using a regular expression.

const capitalizeEveryWord = str= > str.replace(/\b[a-z]/g, char => char.toUpperCase());

capitalizeEveryWord('hello world! '); // 'Hello World! 'Copy the code

15, castArray

This code converts non-numeric values into array objects.

const castArray = val= > (Array.isArray(val) ? val : [val]);

castArray('foo'); // ['foo']
castArray([1]); / / [1]Copy the code

16, compact,

Removes the value false from the array.

const compact = arr= > arr.filter(Boolean);

compact([0.1.false.2.' '.3.'a'.'e' * 23.NaN.'s'.34]); 
// [ 1, 2, 3, 'a', 's', 34 ]Copy the code

17, countOccurrences

Count the number of occurrences of a value in an array

const countOccurrences = (arr, val) = > arr.reduce((a, v) = > (v === val ? a + 1 : a), 0);
countOccurrences([1.1.2.1.2.3].1); / / 3Copy the code

18, Create the Directory

This code snipple uses existSync() to check if the directory exists, and then uses mkdirSync() to create the directory if it doesn’t.

const fs = require('fs');
const createDirIfNotExists = dir= >(! fs.existsSync(dir) ? fs.mkdirSync(dir) :undefined);
createDirIfNotExists('test'); 
// creates the directory 'test', if it doesn't existCopy the code

19, currentURL

Returns the URL address currently accessed.

const currentURL = (a)= > window.location.href;

currentURL(); // 'https://medium.com/@fatosmorina'Copy the code

20, dayOfYear

Returns the current day of the year

const dayOfYear = date= >
  Math.floor((date - new Date(date.getFullYear(), 0.0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date()); / / 272Copy the code

21, decapitalize

Converts the first character of a string to lowercase

const decapitalize = ([first, ...rest]) = >
  first.toLowerCase() + rest.join(' ')

decapitalize('FooBar'); // 'fooBar'Copy the code

section

Thank you for your reading. If you like my sharing, please pay attention, like and forward. Your support is the motivation for my sharing.

Fatos Morina

Source: Medium

reading

127 common JS code snippets, each code can be understood in 30 seconds (2)

127 common JS code snippets, each code can be understood in 30 seconds (3)

127 common JS code snippets, each code can be understood in 30 seconds (4)

More exciting content, please pay attention to the wechat “front-end talent” public number!