preface
A while back, I saw a great GitHub repository, 30-seconds-of-code, whose core idea is “you can learn the functions you need in 30 seconds”. Of these, 30 seconds means that each function implementation is much leaner than you’d expect, which inevitably involves some JavaScript wizardry.
Furthermore, 30-seconds-of-code classifies JavaScript functions into three levels: elementary, medium, and advanced. So, this article has extracted and translated the top 50 beginner level JavaScript functions to share with you.
Start of the text ~
1. all
Check that the supplied function returns true for all values in the array.
- use
Array.prototype.every()
To test whether all elements of the array are presentfn
In returntrue
- Omit the second argument
fn
, the use ofBoolean
To be the default
const all = (arr, fn = Boolean) = > arr.every(fn);
Copy the code
all([4.2.3].x= > x > 1); // true
all([1.2.3]); // true
Copy the code
2. allEqual
Checks whether all elements in the array are equal.
- use
Array.prototype.every()
To check that all elements in the array are the same as the first element. - The use of strict comparison operators to compare elements in arrays is not considered
NaN
Is not equal to.
const allEqual = arr= > arr.every(val= > val === arr[0]);
Copy the code
allEqual([1.2.3.4.5.6]); // false
allEqual([1.1.1.1]); // true
Copy the code
3. and
Checks whether both arguments are true.
- Use logical and on two given values
&&
Operator.
const and = (a, b) = > a && b;
Copy the code
and(true.true); // true
and(true.false); // false
and(false.false); // false
Copy the code
4. any
Checks whether the supplied function returns true for at least one element in the array.
- use
Array.prototype.some()
To test if there are elements in the array based onfn
returntrue
- Omit the second argument
fn
Will,Boolean
As the default.
const any = (arr, fn = Boolean) = > arr.some(fn);
Copy the code
any([0.1.2.0].x= > x >= 2); // true
any([0.0.1.0]); // true
Copy the code
5. approximatelyEqual
Check that the two numbers are roughly equal.
- use
Math.abs()
Add up the difference between the absolute values of two numbersepsilon
Comparison. - Omit the third argument
epsilon
Will be used0.001
To be the default.
const approximatelyEqual = (v1, v2, epsilon = 0.001) = >
Math.abs(v1 - v2) < epsilon;
Copy the code
approximatelyEqual(Math.PI / 2.0.1.5708); // true
Copy the code
6. arithmeticProgression
Creates an array of numbers in an arithmetic series, starting with the given positive integer and working up to the specified limit.
- use
Array.from()
To create a desired length (lim/n
), and usemap
Function to fill it with values in the specified range.
const arithmeticProgression = (n, lim) = >
Array.from({ length: Math.ceil(lim / n) }, (_, i) = > (i + 1) * n );
Copy the code
arithmeticProgression(5.25); // [5, 10, 15, 20, 25]
Copy the code
7. atob
Decodes base-64 encoded string data.
- Creates one based on the given Base-64 encoded string
Buffer
And useBuffer.toString('binary')
To return the decoded string.
const atob = str= > Buffer.from(str, 'base64').toString('binary');
Copy the code
atob('Zm9vYmFy'); // 'foobar'
Copy the code
8. average
Calculate the average of two or more numbers.
- use
Array.prototype.reduce()
Add each value to the accessor, starting with8
. - Divide an array by its length.
const average = (. nums) = >
nums.reduce((acc, val) = > acc + val, 0) / nums.length;
Copy the code
average(... [1.2.3]); / / 2
average(1.2.3); / / 2
Copy the code
10. binomialCoefficient
Count the number of nonrepeating and nonsequential ways to select k items from n items.
- use
Number.isNaN()
To check if one of the two values existsisNaN
. - check
k
Is less than0
Is greater than or equal ton
Is equal to1
或n-1
And returns the appropriate result. - check
n-k
Is less thank
And swap their values accordingly. - from
2
到k
Loop and compute the binomial coefficients. - use
Math.round()
To consider the rounding error in the calculation.
const binomialCoefficient = (n, k) = > {
if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
if (k === 1 || k === n - 1) return n;
if (n - k < k) k = n - k;
let res = n;
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
};
Copy the code
binomialCoefficient(8.2); / / 28
Copy the code
11. both
Checks whether two given functions both return true for the given argument.
- To provide the
args
The result of calling two functions, using logic and (&&
) operator
const both = (f, g) = > (. args) = >f(... args) && g(... args);Copy the code
const isEven = num= > num % 2= = =0;
const isPositive = num= > num > 0;
const isPositiveEven = both(isEven, isPositive);
isPositiveEven(4); // true
isPositiveEven(-2); // false
Copy the code
12. btoa
Creates a Base 64 encoded ASCII string from a string object, where each character in the string is treated as a byte in binary data.
- Creates one for the given string using binary encoding
Buffer
And useBuffer.toString('base')
To return the encoded string.
const btoa = str= > Buffer.from(str, 'binary').toString('base64');
Copy the code
btoa('foobar'); // 'Zm9vYmFy'
Copy the code
Note that the Buffer object needs to be used in the Node environment.
13. byteSize
Returns a string in bytes.
- Converts the given string into a Blob object.
- It is used in bytes
Blob.size
To get the length of the string.
const byteSize = str= > new Blob([str]).size;
Copy the code
byteSize('😀'); / / 4
byteSize('Hello World'); / / 11
Copy the code
14. castArray
If the supplied value is not an array, it is converted to an array.
- use
Array.prototype.isArray()
To determine theval
Whether it is an array and returned as is or encapsulated in an array accordingly.
const castArray = val= > (Array.isArray(val) ? val : [val]);
Copy the code
castArray('foo'); // ['foo']
castArray([1]); / / [1]
Copy the code
15. celsiusToFahrenheit
Convert the Celsius temperature to Fahrenheit.
- Follow the transformation equation
F = 1.8 * C + 32
.
const celsiusToFahrenheit = degrees= > 1.8 * degrees + 32;
Copy the code
celsiusToFahrenheit(33); / / 91.4
Copy the code
16. clampNumber
Restrict num within the inclusion range specified by boundary values A and b.
- if
num
Out of range, returnsnum
. - Otherwise, return the most recent number in the range.
const clampNumber = (num, a, b) = >
Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
Copy the code
clampNumber(2.3.5); / / 3
clampNumber(1, -1, -5); // -1
Copy the code
17. coalesce
Returns the first non-null argument defined
- use
Array.prototype.find()
和Array.prototype.includes()
To find out that the first one does not equalundefined
或null
The value of the.
const coalesce = (. args) = > args.find(v= >! [undefined.null].includes(v));
Copy the code
coalesce(null.undefined.' '.NaN.'Waldo'); / /"
Copy the code
18. compact
Removes false values from the array.
- use
Array.prototype.filter()
To filter false values (false
,null
,0
,""
,undefined
和NaN
).
const compact = arr= > arr.filter(Boolean);
Copy the code
compact([0.1.false.2.' '.3.'a'.'e' * 23.NaN.'s'.34]);
// [ 1, 2, 3, 'a', 's', 34 ]
Copy the code
19. compactWhitespace
Compress whitespace in a string.
- use
String.prototype.replace()
And regular expression to replace all occurrences of 2 or more whitespace strings with a single space.
const compactWhitespace = str= > str.replace(/\s{2,}/g.' ');
Copy the code
compactWhitespace('Lorem Ipsum'); // 'Lorem Ipsum'
compactWhitespace('Lorem \n Ipsum'); // 'Lorem Ipsum'
Copy the code
20. complement
Returns a function that is the logical complement of the given function fn.
- In providing
args
Parameters of the callfn
Results using logical operators!
。
const complement = fn= > (. args) = >! fn(... args);Copy the code
const isEven = num= > num % 2= = =0;
const isOdd = complement(isEven);
isOdd(2); // false
isOdd(3); // true
Copy the code
21. containsWhitespace
Checks for empty characters in a given string.
- use
RegExp.prototype.test()
And an appropriate regular expression to check if a given string contains null characters.
const containsWhitespace = str= > /\s/.test(str);
Copy the code
containsWhitespace('lorem'); // false
containsWhitespace('lorem ipsum'); // true
Copy the code
22. copySign
Returns the absolute value of the first number, but the sign of the second value.
- use
Math.sign()
To check if two numbers have the same sign. - return
x
If they are the same, otherwise return-x
.
const copySign = (x, y) = > Math.sign(x) === Math.sign(y) ? x : -x;
Copy the code
copySign(2.3); / / 2
copySign(2, -3); / / - 2
copySign(-2.3); / / 2
copySign(-2, -3); / / - 2
Copy the code
23. createDirIfNotExists
Create a directory if it does not already exist.
- use
fs.existsSync()
To check if the directory exists, usefs.mkdirSync()
To create a directory.
const fs = require('fs');
const createDirIfNotExists = dir= >(! fs.existsSync(dir) ? fs.mkdirSync(dir) :undefined);
Copy the code
createDirIfNotExists('test');
// creates the directory 'test', if it doesn't exist
Copy the code
24. createElement
Create elements from the string (not added to the document) If a given string contains more than one element, only the first one is returned.
- use
Document.createElement()
To create a new element. - use
Element.innerHTML
Sets its internal HTML to the supplied string argument. - use
ParentNode.firstElementChild
To return the element version of the string.
const createElement = str= > {
const el = document.createElement('div');
el.innerHTML = str;
return el.firstElementChild;
};
Copy the code
const el = createElement(
`
Hello!
`
);
console.log(el.className); // 'container'
Copy the code
25. currentURL
Returns the current URL.
- use
Window.location.href
Gets the current URL.
const currentURL = () = > window.location.href;
Copy the code
currentURL(); // 'https://www.google.com/'
Copy the code
26. dayName
Gets the name of the workday from the Date object.
- use
Date.prototype.toLocaleDateString()
As well as{ weekday: 'long' }
Option to retrieve workdays. - Use the optional second argument to get the name of the specific language, or omit it using the default locale setting.
const dayName = (date, locale) = >
date.toLocaleDateString(locale, { weekday: 'long' });
Copy the code
dayName(new Date()); // 'Saturday'
dayName(new Date('09/23/2020'), 'de-DE'); // 'Samstag'
Copy the code
27. dayOfYear
Gets the day of the year (between 1 and 366) from the Date object.
- use
new Date()
和Date.prototype.getFullYear()
To get the first day of the yearDate
Object. - with
date
Subtract the first day of the year and the number of milliseconds per day to get the result. - use
Math.floor()
Round the resulting figures appropriately to whole numbers.
const dayOfYear = date= >
Math.floor((date - new Date(date.getFullYear(), 0.0)) / 1000 / 60 / 60 / 24);
Copy the code
dayOfYear(new Date()); / / 272
Copy the code
28. daysAgo
The value is a string representing the days n days before today.
- use
new Date
To get the current day,Math.abs()
和Date.prototype.getDate()
Update date accordingly, and useDate.prototype.setDate()
Set the result. - use
Date.prototype.toISOString()
To be returnedyyyy-mm-dd
Format string.
const daysAgo = n= > {
let d = new Date(a); d.setDate(d.getDate() -Math.abs(n));
return d.toISOString().split('T') [0];
};
Copy the code
daysAgo(20); // 2020-09-16 (if current date is 2020-10-06)
Copy the code
29. daysFromNow
Calculates the date n days from today as a string representation.
- use
new Date()
Get the current day,Math.abs()
和Date.prototype.getDate()
To update popularity accordingly, and useDate.prototype.setDate()
To set the result. - use
Date.prototype.toISOString()
To return theyyyy-mm-dd
Format string.
const daysFromNow = n= > {
let d = new Date(a); d.setDate(d.getDate() +Math.abs(n));
return d.toISOString().split('T') [0];
};
Copy the code
daysFromNow(5); // 2020-10-13 (if current date is 2020-10-08)
Copy the code
30. degreesToRads
Change the Angle from degrees to arcs.
- use
Math.PI
And the formula for degrees to radians to convert an Angle from degrees to arcs.
const degreesToRads = deg= > (deg * Math.PI) / 180.0;
Copy the code
degreesToRads(90.0); / / ~ 1.5708
Copy the code
31. difference
Computes the difference between two arrays without filtering out duplicate values.
- According to the
b
createSet
Collection to getb
Unique value in. - right
a
useArray.prototype.filter()
To keep awayb
, and the use ofSet.prototype.has()
.
const difference = (a, b) = > {
const s = new Set(b);
return a.filter(x= >! s.has(x)); };Copy the code
difference([1.2.3.3], [1.2.4]); / / [3, 3]
Copy the code
32. digitize
Converts a number to an array of numbers, removing its sign if necessary.
- use
Math.abs()
Remove the sign from the number. - Convert numbers to strings using the expansion operator (
.
) to construct an array. - use
Array.prototype.map()
和parseInt()
Convert each value to an integer.
const digitize = n= > [...`The ${Math.abs(n)}`].map(i= > parseInt(i));
Copy the code
digitize(123); / / [1, 2, 3]
digitize(-123); / / [1, 2, 3]
Copy the code
33. distance
Calculate the distance between two points.
- use
Math.hypot()
To calculate the Euclidean distance between two points.
const distance = (x0, y0, x1, y1) = > Math.hypot(x1 - x0, y1 - y0);
Copy the code
distance(1.1.2.3); / / ~ 2.2361
Copy the code
34. divmod
Returns an array of the quotient and remainder of a given number.
- use
Math.floor()
In order to getx / y
In the business. - Get using the modular operator
x / y
The remainder.
const divmod = (x, y) = > [Math.floor(x / y), x % y];
Copy the code
divmod(8.3); / / (2, 2)
divmod(3.8); / / [0, 3]
divmod(5.5); / / (1, 0]
Copy the code
35. drop
Creates an array with n elements removed from the left.
- use
Array.prototype.slice()
To remove elements that are numbered from the left. - Omit the last argument
n
, the default value is1
.
const drop = (arr, n = 1) = > arr.slice(n);
Copy the code
drop([1.2.3]); / / [2, 3]
drop([1.2.3].2); / / [3]
drop([1.2.3].42); / / []
Copy the code
36. dropRight
Creates an array with n elements removed from the right.
- use
Array.prototype.slice()
To remove elements that are numbered from the right. - Omit the last argument
n
, the default value is1
.
const dropRight = (arr, n = 1) = > arr.slice(0, -n);
Copy the code
dropRight([1.2.3]); / / [1, 2]
dropRight([1.2.3].2); / / [1]
dropRight([1.2.3].42); / / []
Copy the code
37. either
Checks whether at least one function returns true for a given set of arguments.
- In use provided by the entry
args
Use logic and operators on the result of calling a function (||
) - Use the logical or (
||
) operator on the result of calling the two functions with the suppliedargs
.
const either = (f, g) = > (. args) = >f(... args) || g(... args);Copy the code
const isEven = num= > num % 2= = =0;
const isPositive = num= > num > 0;
const isPositiveOrEven = either(isPositive, isEven);
isPositiveOrEven(4); // true
isPositiveOrEven(3); // true
Copy the code
38. elementIsFocused
Checks whether the given element is focused.
- use
Document.activeElement
To determine whether a given element is focused.
const elementIsFocused = el= > (el === document.activeElement);
Copy the code
elementIsFocused(el); // true if the element is focused
Copy the code
39. everyNth
Returns the NTH of each element in the array.
- use
Array.prototype.filter()
To create an array containing each of the given arraysnth
A new array of elements.
const everyNth = (arr, nth) = > arr.filter((e, i) = > i % nth === nth - 1);
Copy the code
everyNth([1.2.3.4.5.6].2); // [2, 4, 6]
Copy the code
40. expandTabs
Convert tabs to Spaces, where each TAB corresponds to a count space.
- use
String.prototype.replace()
, regular expressions,String.prototype.repeat()
To replace each TAB character withcount
The blank space.
const expandTabs = (str, count) = > str.replace(/\t/g.' '.repeat(count));
Copy the code
expandTabs('\t\tlorem'.3); // ' lorem'
Copy the code
41. factorial
Compute the factorial of a number.
- Use recursion.
- if
n
Less than or equal to1
, the return1
. - Otherwise, return
n
And the product ofn-1
The factorial. - if
n
If it is negative, returnTypeError
.
const factorial = n= >
n < 0
? (() = > {
throw new TypeError('Negative numbers are not allowed! ');
})()
: n <= 1
? 1
: n * factorial(n - 1);
Copy the code
factorial(6); / / 720
Copy the code
42. fahrenheitToCelsius
Convert Fahrenheit to Celsius.
- follow
C = (F - 32) * 5/9
The conversion formula of.
const fahrenheitToCelsius = degrees= > (degrees - 32) * 5 / 9;
Copy the code
fahrenheitToCelsius(32); / / 0
Copy the code
43. filterNonUnique
Filter out non-unique values to create an array.
- use
new Set()
And the expansion operator.
To create contains inarr
An array of unique values in. - use
Array.prototype.filter()
To create an array that contains only unique values.
const filterNonUnique = arr= >
[...new Set(arr)].filter(i= > arr.indexOf(i) === arr.lastIndexOf(i));
Copy the code
filterNonUnique([1.2.2.3.4.4.5]); / / [1, 3, 5]
Copy the code
44. filterUnique
Creates an array with filtered unique values.
- use
new Set()
和.
The expansion operator is inarr
Creates an array of unique values in. - use
Array.prototype.filter()
To create an array that contains only unique values.
const filterNonUnique = arr= >
[...new Set(arr)].filter(i= > arr.indexOf(i) === arr.lastIndexOf(i));
Copy the code
filterNonUnique([1.2.2.3.4.4.5]); / / [1, 3, 5]
Copy the code
45. findLast
Finds the last element of the given function that returns true.
- use
Array.prototype.filter()
To removefn
Returns the element false. - use
Array.prototype.pop()
To get the last element of the filtered array.
const findLast = (arr, fn) = > arr.filter(fn).pop();
Copy the code
findLast([1.2.3.4].n= > n % 2= = =1); / / 3
Copy the code
46. formatNumber
Format numbers using local numbers.
- use
Number.prototype.toLocaleString()
To convert a number to a local number format delimiter.
const formatNumber = num= > num.toLocaleString();
Copy the code
formatNumber(123456); / / '123456' in ` en - US `
formatNumber(15675436903); / / '15.675.436.903 ` in DE - DE `
Copy the code
47. fromTimestamp
Create a Date object based on the Unix timestamp.
- Multiply by by
1000
To convert the timestamp to seconds. - use
new Date()
To create a new oneDate
Object.
const fromTimestamp = timestamp= > new Date(timestamp * 1000);
Copy the code
fromTimestamp(1602162242); / / the T13:2020-10-08 HKT. 000 z
Copy the code
48. functionName
Print the name of the function.
- use
console.debug()
And the function passed inname
Property to print the name of the function to the console. - Returns the given function
fn
.
const functionName = fn= > (console.debug(fn.name), fn);
Copy the code
let m = functionName(Math.max)(5.6);
// max (logged in debug channel of console)
// m = 6
Copy the code
49. gcd
Computes the greatest common divisor between two or more numbers/arrays.
- The inside of the
_gcd
The function will use recursion. - The base case is when
y
Is equal to the0
In this case, returnsx
. - Otherwise, return
y
GCD and divisionx/y
The remainder.
const gcd = (. arr) = > {
const _gcd = (x, y) = >(! y ? x : gcd(y, x % y));return [...arr].reduce((a, b) = > _gcd(a, b));
};
Copy the code
gcd(8.36); / / 4gcd(... [12.8.32]); / / 4
Copy the code
50. getAncestors
Returns all ancestors of the element from the document root to the given element.
- use
Node.parentNode
和while
Loop to move up the element’s ancestor tree. - use
Array. The prototype. The unshift ()
Adds each new ancestor to the beginning of the array.
const getAncestors = el= > {
let ancestors = [];
while (el) {
ancestors.unshift(el);
el = el.parentNode;
}
return ancestors;
};
Copy the code
getAncestors(document.querySelector('nav'));
// [document, html, body, header, nav]
Copy the code
reference
30-seconds-of-code
❤️ Love triple punch
Writing is not easy, if you can, please point a praise, it will become my motivation to keep writing, Aoli!!
I am Wu Liu, like innovation, tamping source Code, focus on Vue3 source Code, Vite source Code, front-end engineering and other technical fields to share, welcome to pay attention to my “wechat public number: Code Center”.