Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

background

This article is the front end of the common utility functions, the main content includes: array class, browser class, date class, function class, mathematics class, media class, node class, object class, string class, type detection class, regular expression class and so on.

The body of the

An array of class

  • arrayMax
  • arrayMin
  • chunk
  • compact
  • countOccurrences
  • deepFlatten
  • difference
  • distinctValuesOfArray
  • dropElements
  • everyNth
  • filterNonUnique
  • flatten
  • flattenDepth
  • groupBy
  • head
  • initial
  • initializeArrayWithRange
  • initializeArrayWithValues
  • intersection
  • last
  • mapObject
  • nthElement
  • pick
  • pull
  • remove
  • sample
  • shuffle
  • similarity
  • symmetricDifference
  • tail
  • take
  • takeRight
  • union
  • without
  • zip

The browser

  • bottomVisible
  • currentURL
  • elementIsVisibleInViewport
  • getScrollPosition
  • getURLParameters
  • redirect
  • scrollToTop

time

  • getDaysDiffBetweenDates
  • JSONToDate
  • toEnglishDate

function

  • chainAsync
  • compose
  • curry
  • functionName
  • pipe
  • promisify
  • runPromisesInSeries
  • sleep

mathematics

  • arrayAverage
  • arraySum
  • collatz
  • digitize
  • distance
  • factorial
  • fibonacci
  • gcd
  • hammingDistance
  • isDivisible
  • isEven
  • lcm
  • median
  • palindrome
  • percentile
  • powerset
  • randomIntegerInRange
  • randomNumberInRange
  • round
  • standardDeviation

The media

  • speechSynthesis

node

  • JSONToFile
  • readFileLines

object

  • cleanObj
  • objectFromPairs
  • objectToPairs
  • shallowClone
  • truthCheckCollection

string

  • anagrams
  • capitalize
  • capitalizeEveryWord
  • escapeRegExp
  • fromCamelCase
  • reverseString
  • sortCharactersInString
  • toCamelCase
  • truncateString

tool

  • coalesce
  • coalesceFactory
  • extendHex
  • getType
  • hexToRGB
  • isArray
  • isBoolean
  • isFunction
  • isNumber
  • isString
  • isSymbol
  • RGBToHex
  • timeTaken
  • toOrdinalSuffix
  • UUIDGenerator
  • validateEmail
  • validateNumber

An array of

☝ Back to directory

arrayMax

Returns the maximum value in the array.

Combine math.max () with the extended operator (…) Used in combination to get the maximum value in the array.

const arrayMax = arr= > Math.max(... arr);// arrayMax([10, 1, 5]) -> 10
Copy the code

☝ Back to directory

arrayMin

Returns the minimum value in the array.

Combine math.min () with the extended operator (…) Used in combination to get the minimum value in the array.

const arrayMin = arr= > Math.min(... arr);// arrayMin([10, 1, 5]) -> 1
Copy the code

☝ Back to directory

chunk

Divides an array block into smaller arrays of a specified size.

Create a new Array using array.from (), which matches the number of blocks to be generated. Use array.slice () to map each element of the new Array to a size-length block. If the original array is not evenly split, the final block contains the remaining elements.

const chunk = (arr, size) = >
Array.from({length: Math.ceil(arr.length / size)}, (v, i) = > arr.slice(i * size, i * size + size));
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]]
Copy the code

☝ Back to directory

compact

Removes falsey value from array.

Filter out falsey values (false, null, 0, “”, undefined, and NaN) using array.filter ().

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

☝ Back to directory

countOccurrences

Count the number of occurrences of values in the array.

Use array.reduce () to increment the counter each time a particular value in the Array is encountered.

const countOccurrences = (arr, value) = > arr.reduce((a, v) = > v === value ? a + 1 : a + 0.0);
// countOccurrences([1,1,2,1,2,3], 1) -> 3
Copy the code

☝ Back to directory

deepFlatten

Deep splice array.

Use recursion. Use array.concat () with empty arrays ([]) and cross-page operators (…) To splice the array. Recursively assemble each element as an array.

const deepFlatten = arr= >[].concat(... arr.map(v= > Array.isArray(v) ? deepFlatten(v) : v));
/ / deepFlatten ([1, [2], [[3], 4, 5]] - > [1, 2, 3, 4, 5]
Copy the code

☝ Back to directory

difference

Returns the difference between two arrays.

Create a Set from b, then use array.filter () on to preserve only values not contained in a and b.

const difference = (a, b) = > { const s = new Set(b); return a.filter(x= >! s.has(x)); };// difference([1,2,3], [1,2,4]) -> [3]
Copy the code

☝ Back to directory

distinctValuesOfArray

Returns all the different values of the array.

Using ES6 Set and… The REST operator discards all duplicate values.

const distinctValuesOfArray = arr= > [...new Set(arr)];
/ / distinctValuesOfArray (,2,2,3,4,4,5 [1]) - > [1, 2, 3, 4, 5]
Copy the code

☝ Back to directory

dropElements

Removes an element from the array until the passed function returns true. Returns the remaining elements of the array. Loop through the Array, using array.shift () to remove the first element of the Array until the function returns true. Return the remaining elements.

const dropElements = (arr, func) = > {
while (arr.length > 0 && !func(arr[0])) arr.shift();
return arr;
};
/ / dropElements ([1, 2, 3, 4], n = > n > = 3) - > [3, 4]
Copy the code

☝ Back to directory

everyNth

Returns each NTH element in the array.

Use array.filter () to create a new Array containing each NTH element of the given Array.

const everyNth = (arr, nth) = > arr.filter((e, i) = > i % nth === 0);
// everyNth([1,2,3,4,5,6], 2) -> [1, 3, 5]
Copy the code

☝ Back to directory

filterNonUnique

Filter out non-unique values in the array.

For arrays that contain only unique values, use array.filter ().

const filterNonUnique = arr= > arr.filter(i= > arr.indexOf(i) === arr.lastIndexOf(i));
/ / filterNonUnique (,2,2,3,4,4,5 [1]) - >,3,5 [1]
Copy the code

☝ Back to directory

flatten

Splice an array.

Use array.reduce () to get all the elements in the Array and concat() to piece them together.

const flatten = arr= > arr.reduce((a, v) = > a.concat(v), []);
/ / flatten ([[2] 1, 3, 4]] - > [1, 2, 3, 4]
Copy the code

☝ Back to directory

flattenDepth

Assembles an array up to the specified depth.

Using recursion, drop depth to 1 for each layer. Use array.reduce () and array.concat () to merge elements or arrays. Basically, we stop recursion for depth equal to 1. The second element is omitted, and depth is only collated to the depth of 1 (single collation).

const flattenDepth = (arr, depth = 1) = >depth ! =1 ? arr.reduce((a, v) = > a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), [])
: arr.reduce((a, v) = > a.concat(v), []);
/ / flattenDepth ([1, [2], [[[3], 4, 5]], 2) - > [[3] 1, 2, 4, 5]
Copy the code

☝ Back to directory

groupby

Groups array elements according to the given function.

Use array.map () to map the values of an Array to function or attribute names. Use array.reduce () to create an object where the keys are generated from the result of the mapping.

const groupBy = (arr, func) = >
arr.map(typeof func === 'function' ? func : val= > val[func])
.reduce((acc, val, i) = > { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {});
/ / groupBy ([6.1, 4.2, 6.3], Math. The floor) - > {4: [4.2], 6: [6.1, 6.3]}
// groupBy(['one', 'two', 'three'], 'length') -> {3: ['one', 'two'], 5: ['three']}
Copy the code

☝ Back to directory

head

Returns the head of the list.

Use arr[0] to return the first element of the passed array.

const head = arr= > arr[0];
/ / the head ([1, 2, 3]) - > 1
Copy the code

☝ Back to directory

initial

Returns all elements except the last array.

Slice (0,-1) returns the last element of the array.

const initial = arr= > arr.slice(0, -1);
/ / initial () [1, 2, 3] - > [1, 2]
Copy the code

☝ Back to directory

initializeArrayWithRange

Initializes an array containing numbers in the specified range.

Use Array(end-start) to create an Array array.map () of the required length to fill the desired values in the region. Start can be omitted to use the default value 0.

const initializeArrayWithRange = (end, start = 0) = >
Array.from({ length: end - start }).map((v, i) = > i + start);
/ / initializeArrayWithRange (5) - >,1,2,3,4 [0]
Copy the code

☝ Back to directory

initializeArrayWithValues

Initializes and populates an array with the specified value.

Create an Array of the desired length using Array(n),fill(v) to fill the desired values. You can omit value to use the default value 0.

const initializeArrayWithValues = (n, value = 0) = > Array(n).fill(value);
/ / initializeArrayWithValues (5, 2) - >,2,2,2,2 [2]
Copy the code

☝ Back to directory

intersection

Returns a list of elements that exist in both arrays.

Create a Set from b, then use array.filter ()on a to preserve only the values contained in b.

const intersection = (a, b) = > { const s = new Set(b); return a.filter(x= > s.has(x)); };
// intersection([1,2,3], [4,3]) -> [2,3]
Copy the code

☝ Back to directory

last

Returns the last element in the array.

Arr. Length-1 computs the index of the last element of a given array and returns it.

const last = arr= > arr[arr.length - 1];
/ / the last ([1, 2, 3]) - > 3
Copy the code

☝ Back to directory

mapObject

Use a function to map the values of an array to an object, where a key-value pair consists of the original values as keys and mapped values.

Anonymous internal function scopes are used to declare undefined memory space, and closures are used to store return values. Using the new Array puts the mapping of that Array to a function on its data set, and the comma operator returns the second step without needing to move from one context to another (due to closure and operation order).

const mapObject = (arr, fn) = > 
(a= > (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) = > (acc[val] = a[1][ind], acc), {}) )) ( );
/* const squareIt => mapObject(arr, a => a*a) squareIt([1,2,3]) {1: 1,2:4, 3: 9} */
Copy the code

☝ Back to directory

nthElement

Returns the NTH element of the array.

Use array.slice () to get an Array containing the NTH element. If the index is out of bounds, return []. Omit the second argument n to get the first element of the array.

const nthElement = (arr, n=0) = > (n>0? arr.slice(n,n+1) : arr.slice(n))[0];
// nthElement(['a','b','c'],1) -> 'b'
// nthElement(['a','b','b'],-3) -> 'a'
Copy the code

☝ Back to directory

pick

Selects the key-value pair corresponding to the given key from the object.

Use array.reduce () to convert the filtered/selected key back to an object with the corresponding key-value pair if the key exists in obJ.

const pick = (obj, arr) = >
arr.reduce((acc, curr) = > (curr in obj && (acc[curr] = obj[curr]), acc), {});
// pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 }
Copy the code

☝ Back to directory

pull

Mutates the original array to filter out the specified value.

Use array.filter () and array.includes () to pull out unwanted values. Using array.length = 0 resets the length in the passed Array to zero and sets it to array.push () to populate it with only the extracted values.

const pull = (arr, ... args) = > {
let pulled = arr.filter((v, i) = >! args.includes(v)); arr.length =0; pulled.forEach(v= > arr.push(v));
};
// let myArray = ['a', 'b', 'c', 'a', 'b', 'c'];
// pull(myArray, 'a', 'c');
// console.log(myArray) -> [ 'b', 'b' ]
Copy the code

☝ Back to directory

remove

Removes the element from the array for which the given function returns false. Use array.filter () to find Array elements that return truthy values and array.reduce () to remove elements using array.splice (). Use three arguments (func value, index, array to call the function).

const remove = (arr, func) = >
Array.isArray(arr) ? arr.filter(func).reduce((acc, val) = > {
arr.splice(arr.indexOf(val), 1); returnacc.concat(val); } []) : [];// remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4]
Copy the code

☝ Back to directory

sample

Returns a random element in an array.

Use math.random () to generate a random number, multiply it by length, and use Math to round it to the nearest integer math.floor (). This method also works with strings.

const sample = arr= > arr[Math.floor(Math.random() * arr.length)];
// sample([3, 7, 9, 11]) -> 9
Copy the code

☝ Back to directory

shuffle

The order of a random set of values.

Use array.sort () to reorder elements using math.random () in the comparator.

const shuffle = arr= > arr.sort(() = > Math.random() - 0.5);
/ / shuffle ([1, 2, 3]) - >,3,1 [2]
Copy the code

☝ Back to directory

similarity

Returns an array of elements displayed in both arrays.

To delete values that do not belong to values, use filter() and use includes().

const similarity = (arr, values) = > arr.filter(v= > values.includes(v));
// similarity([1,2,3], [1,2,4]) -> [1,2]
Copy the code

☝ Back to directory

symmetricDifference

Returns the symmetry difference between two arrays.

Create a Set from each Array, and then use array.filter () for each of them to preserve only values that are not included in the other values.

const symmetricDifference = (a, b) = > {
const sA = new Set(a), sB = new Set(b);
return [...a.filter(x= >! sB.has(x)), ... b.filter(x= >! sA.has(x))]; }// symmetricDifference([1,2,3], [1,2,4]) -> [3,4]
Copy the code

☝ Back to directory

tail

Returns all elements in the array except the first.

Arr.slice (1) is returned if the array’s length is greater than 1, otherwise the entire array is returned.

const tail = arr= > arr.length > 1 ? arr.slice(1) : arr;
/ / tail () [1, 2, 3] - > [2, 3]
// tail([1]) -> [1]
Copy the code

☝ Back to directory

take

Returns an array with n elements removed from the start.

Use array.slice () to create a slice of the Array containing the n elements taken from the beginning.

const take = (arr, n = 1) = > arr.slice(0, n);
// take([1, 2, 3], 5) -> [1, 2, 3]
// take([1, 2, 3], 0) -> []
Copy the code

☝ Back to directory

takeRight

Returns an array with n elements removed from the end.

Use array.slice () to create a slice of the Array containing the n element fetched from the end.

const takeRight = (arr, n = 1) = > arr.slice(arr.length - n, arr.length);
// takeRight([1, 2, 3], 2) -> [ 2, 3 ]
// takeRight([1, 2, 3]) -> [3]
Copy the code

☝ Back to directory

union

Returns each element that exists in either array.

Create a Set that contains all the values of a and B and convert them to an array.

const union = (a, b) = > Array.from(new Set([...a, ...b]));
// union([1,2,3], [4,3]) -> [1,2,3,4]
Copy the code

☝ Back to directory

without

Filter the element in the array that has one of the specified values.

Use array.filter () to create an Array that is not included (use! Array.includes()) all the given values.

const without = (arr, ... args) = > arr.filter(v= >! args.includes(v));// without([2, 1, 2, 3], 1, 2) -> [3]
Copy the code

☝ Back to directory

zip

Creates an array of elements grouped based on positions in the original array.

Use math.max.apply () to get the longest array of parameters. Create an Array with that length as the return value, and use the map function to create an Array of grouped elements array.from (). If the Array of parameters has different lengths, use undefined if no value is found.

const zip = (. arrays) = > {
const maxLength = Math.max(... arrays.map(x= > x.length));
return Array.from({length: maxLength}).map((_, i) = > {
return Array.from({length: arrays.length}, (_, k) = >arrays[k][i]); })}//zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]]
//zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]]
Copy the code

The browser

☝ Back to directory

bottomVisible

Returns true if the bottom of the page is visible, false otherwise.

Use scrollY, scrollHeight, and clientHeight to determine if the bottom of the page is visible.

const bottomVisible = () = >
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
// bottomVisible() -> true
Copy the code

☝ Back to directory

currentURL

Returns the current URL.

Use window.location.href to get the current URL.

const currentURL = () = > window.location.href;
// currentUrl() -> 'https://google.com'
Copy the code

☝ Back to directory

elementIsVisibleInViewport

Returns true if the specified element is visible in the viewport, false otherwise.

Use Element. GetBoundingClientRect (), and the window. The inner (Width | Height) value to determine whether a given Element in the viewport. Omit the second argument to determine whether the element is fully visible, or specify true to determine whether it is partially visible.

const elementIsVisibleInViewport = (el, partiallyVisible = false) = > {
const { top, left, bottom, right } = el.getBoundingClientRect();
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
// elementIsVisibleInViewport(el) -> false (not fully visible)
// elementIsVisibleInViewport(el, true) -> true (partially visible)
Copy the code

☝ Back to directory

getScrollPosition

Returns the scroll position of the current page.

PageXOffset and pageYOffset are used if defined, otherwise scrollLeft and scrollTop are used. You can omit el to use the default value for window.

const getScrollPosition = (el = window) = >
({x: (el.pageXOffset ! = =undefined)? el.pageXOffset : el.scrollLeft,y: (el.pageYOffset ! = =undefined)? el.pageYOffset : el.scrollTop});// getScrollPosition() -> {x: 0, y: 200}
Copy the code

☝ Back to directory

getURLParameters

Returns an object containing the current URL argument.

Use match() with the appropriate regular expression to get all key-value pairs, which array.reduce () maps and merges into a single object. Pass location.search as a parameter to be applied to the current URL.

const getURLParameters = url= >
url.match(/([^?=&]+)(=([^&]*))/g).reduce(
(a, v) = > (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {}
);
// getURLParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
Copy the code

☝ Back to directory

redirect

Redirect to the specified URL.

Use window.location.href or window.location.replace() to redirect to the URL. Pass the second argument to simulate link click (true- default) or HTTP redirect (false).

const redirect = (url, asLink = true) = >
asLink ? window.location.href = url : window.location.replace(url);
// redirect('https://google.com')
Copy the code

☝ Back to directory

scrollToTop

Scroll smoothly to the top of the page.

Use the document. The documentElement. ScrollTop or document. The body. The scrollTop get distance from the top. Roll a small part of the distance from the top. Use Windows. RequestAnimationFrame () for animation processing rolling.

const scrollToTop = () = > {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8); }};// scrollToTop()
Copy the code

The date of

☝ Back to directory

getDaysDiffBetweenDates

Returns the difference (in days) between two dates.

Calculates the difference between Date objects (in days).

const getDaysDiffBetweenDates = (dateInitial, dateFinal) = > (dateFinal - dateInitial) / (1000 * 3600 * 24);
// getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9
Copy the code

☝ Back to directory

JSONToDate

Convert a JSON object to a date.

Convert a JSON-formatted Date to a readable format (DD/MM/YYYY) using Date().

const JSONToDate = arr= > {
const dt = new Date(parseInt(arr.toString().substr(6)));
return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }`
};
// JSONToDate(/Date(1489525200000)/) -> "14/3/2017"
Copy the code

☝ Back to directory

toEnglishDate

Converts a date from a US format to an English format.

Convert dates from the American format to the English format using date.toisostring (), split(‘T’), and replace(). If the passed time cannot be converted to a date, an error is thrown.

const toEnglishDate  = (time) = >
{try{return new Date(time).toISOString().split('T') [0].replace(/-/g.'/')}catch(e){return}};
// toEnglishDate('09/21/2010') -> '21/09/2010'
Copy the code

The function class

☝ Back to directory

chainAsync

Chain asynchronous functions.

Loop through the array of functions that contain asynchronous events, calling next when each asynchronous event completes.

const chainAsync = fns= > { let curr = 0; const next = () = > fns[curr++](next); next(); };
/* chainAsync([ next => { console.log('0 seconds'); setTimeout(next, 1000); }, next => { console.log('1 second');  setTimeout(next, 1000); }, next => { console.log('2 seconds'); } ]) */
Copy the code

☝ Back to directory

compose

Performs a combination of functions from right to left.

Perform a combination of functions from right to left using array.reduce (). The last (rightmost) function can take one or more arguments; The remaining functions must be unary.

const compose = (. fns) = > fns.reduce((f, g) = > (. args) = >f(g(... args)));/*
const add5 = x => x + 5
const multiply = (x, y) => x * y
const multiplyAndAdd5 = compose(add5, multiply)
multiplyAndAdd5(5, 2) -> 15
*/
Copy the code

☝ Back to directory

curry

Curries a function.

Use recursion. If the number of arguments (variables) provided is sufficient, call the passed function args f. Otherwise, return the extension function f that requires the remaining parameters. If you want a function that takes a variable number of arguments (such as math.min ()), you can choose to pass the number of arguments to the second parameter (the arity of the mutable function).

const curry = (fn, arity = fn.length, ... args) = >arity <= args.length ? fn(... args) : curry.bind(null, fn, arity, ... args);// curry(Math.pow)(2)(10) -> 1024
// curry(Math.min, 3)(10)(50)(2) -> 2
Copy the code

☝ Back to directory

functionName

Record the name of the function.

Use console.debug() and the name attribute of the passed method to record the method’s name to the console’s Debug channel.

const functionName = fn= > (console.debug(fn.name), fn);
// functionName(Math.max) -> max (logged in debug channel of console)
Copy the code

☝ Back to directory

pipe

Performs a left-to-right combination of functions.

Use array.reduce () with extended operators (…) Performs a left-to-right combination of functions. The first (leftmost) function can take one or more arguments; The remaining functions must be unary.

const pipeFunctions = (. fns) = > fns.reduce((f, g) = > (. args) = >g(f(... args)));/*
const add5 = x => x + 5
const multiply = (x, y) => x * y
const multiplyAndAdd5 = pipeFunctions(multiply, add5)
multiplyAndAdd5(5, 2) -> 15
*/
Copy the code

☝ Back to directory

promisify

Transform the asynchronous function to return a promise.

Using ingratiation returns a function that returns the Promise of calling the original function. The use of… The REST operator passes in all the arguments. In node 8 +, util.promisify is available

const promisify = func= >
(. args) = >
new Promise((resolve, reject) = >func(... args,(err, result) = >
err ? reject(err) : resolve(result))
);
// const delay = promisify((d, cb) => setTimeout(cb, d))
// delay(2000).then(() => console.log('Hi! ')) -> Promise resolves after 2s
Copy the code

☝ Back to directory

runPromisesInSeries

Run a series of commitment series.

Use array.reduce () to create a chain of commitments, each of which returns the next commitment upon resolution.

const runPromisesInSeries = ps= > ps.reduce((p, next) = > p.then(next), Promise.resolve());
// const delay = (d) => new Promise(r => setTimeout(r, d))
// runPromisesInSeries([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
Copy the code

☝ Back to directory

sleep

Delay the execution of asynchronous functions.

Delay the execution of part of an async function, put it into a sleep state, and return a Promise.

const sleep = ms= > new Promise(resolve= > setTimeout(resolve, ms));
/* async function sleepyWork() { console.log('I\'m going to sleep for 1 second.'); await sleep(1000); console.log('I woke up after 1 second.'); } * /
Copy the code

mathematics

☝ Back to directory

arrayAverage

Returns the average value of an array of numbers.

Each value is added to the accumulator using array.reduce () and initialized with a value of 0, divided by the length of the Array.

const arrayAverage = arr= > arr.reduce((acc, val) = > acc + val, 0) / arr.length;
/ / arrayAverage ([1, 2, 3]) - > 2
Copy the code

☝ Back to directory

arraySum

Returns the sum of an array of numbers.

Each value is added to the accumulator using array.reduce () and initialized with a value of 0.

const arraySum = arr= > arr.reduce((acc, val) = > acc + val, 0);
/ / arraySum ([1, 2, 3, 4]) - > 10
Copy the code

☝ Back to directory

collatz

Apply the Collatz algorithm.

If n is even, return n/2. Otherwise 3n+1 is returned.

const collatz = n= > (n % 2= =0)? (n /2) : (3 * n + 1);
// collatz(8) --> 4
// collatz(5) --> 16
Copy the code

☝ Back to directory

collatz

Converts numbers to arrays of numbers.

Converts numbers to strings, generating arrays using extended operators in ES6 ([…string]). Convert each value to an integer using array.map () and parseInt().

const digitize = n= > [...' '+n].map(i= > parseInt(i));
// digitize(2334) -> [2, 3, 3, 4]
Copy the code

☝ Back to directory

digitize

Returns the distance between two points.

Calculate the Euclidean distance between two points using math.hypot ().

const distance = (x0, y0, x1, y1) = > Math.hypot(x1 - x0, y1 - y0);
/ / short (1, 1, 2, 3) - > 2.23606797749979
Copy the code

☝ Back to directory

distance

Compute the factorial of a number.

Use recursion. If n is less than or equal to 1, return 1. Otherwise, return the product of n and the factorial of n-1. If n is negative, an exception is thrown.

const factorial = n= >
n < 0 ? (() = > { throw new TypeError('Negative numbers are not allowed! ') })()
: n <= 1 ? 1 : n * factorial(n - 1);
// factorial(6) -> 720
Copy the code

☝ Back to directory

fibonacci

Generates an array containing the Fibonacci sequence up to the NTH entry.

Creates an empty array of the specified length, initializing the first two values (0 and 1). Use array.reduce () to add values to an Array by using the sum of the first two values, but not the first two.

const fibonacci = n= >
Array(n).fill(0).reduce((acc, val, i) = > acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
/ / the Fibonacci (5) - >,1,1,2,3 [0]
Copy the code

☝ Back to directory

gcd

Computes the largest common divisor between two numbers.

Use recursion. The base case is when y is equal to 0. In this case, return x. Otherwise, return the GCD of y and the rest of the division x/y.

const gcd = (x, y) = >! y ? x : gcd(y, x % y);// gcd (8, 36) -> 4
Copy the code

☝ Back to directory

hammingDistance

Calculate the Hamming distance between two values.

Use the XOR operator (^) to find the bit difference between two numbers, which is converted to a binary string using toString(2). Use match(/1/g) to count and return the number of 1s in the string. .

const hammingDistance = (num1, num2) = >
((num1 ^ num2).toString(2).match(/1/g) | |' ').length;
/ / hammingDistance - > 1, 2, 3)
Copy the code

☝ Back to directory

isDivisible

Checks whether the first numeric argument is divisible by another numeric variable.

Use the modular operator (%) to check if the remainder is equal to 0.

const isDivisible = (dividend, divisor) = > dividend % divisor === 0;
/ / isDivisible (6, 3) - > true
Copy the code

☝ Back to directory

iseven

Returns true if the given number is even, false otherwise.

Check whether a number is odd or uses the modulus (%) operator. Returns true if the number is even, false if the number is odd.

const isEven = num= > num % 2= = =0;
// isEven(3) -> false
Copy the code

☝ Back to directory

lcm

Returns the least common multiple of the two numbers.

Use the maximum common divisor (GCD) formula and math.abs () to determine the least common multiple. The GCD formula uses recursion.

const lcm = (x,y) = > {
const gcd = (x, y) = >! y ? x : gcd(y, x % y);return Math.abs(x*y)/(gcd(x,y));
};
/ / LCM (12, 7) - > 84
Copy the code

☝ Back to directory

median

Returns the middle value of an array of numbers.

Find the middle of the Array and use array.sort () to sort the values. If length is odd, return the midpoint number, otherwise the average of the two intermediate numbers.

const median = arr= > {
const mid = Math.floor(arr.length / 2), nums = arr.sort((a, b) = > a - b);
return arr.length % 2! = =0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
};
/ / median ([5,6,50,1, - 5]) - > 5
/ / median ([0, 10, 2, 7]) - > 3.5
Copy the code

☝ Back to directory

palindrome

Returns true if the given string is a palindrome, false otherwise.

Convert the string toLowerCase() and use replace() to remove non-alphanumeric characters from it. Then split(“) to individual characters,reverse(),join(“), compare it to the original, irreversible string, and convert it to tolowerCase().

const palindrome = str= > {
const s = str.toLowerCase().replace(/[\W_]/g.' ');
return s === s.split(' ').reverse().join(' ');
}
// palindrome('taco cat') -> true
Copy the code

☝ Back to directory

percentile

Use the percentage formula to calculate how many numbers in a given array are less than or equal to a given value.

Use array.reduce () to calculate how many of the values are the same, and apply the percentage formula.

const percentile = (arr, val) = >
100 * arr.reduce((acc,v) = > acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length;
Percentile ([1,2,3,4,5,6,7,8,9,10], 6) -> 55
Copy the code

☝ Back to directory

powerset

Returns the true subset of the given array.

Combine array.reduce () with array.map () to loop through elements and merge them into an Array containing all combinations.

const powerset = arr= >
arr.reduce((a, v) = > a.concat(a.map(r= > [v].concat(r))), [[]]);
// PowerSet ([1,2]) -> [[], [1], [2], [2,1]]
Copy the code

☝ Back to directory

randomIntegerInRange

Returns a random integer in the specified range.

Use math.random () to generate a random number and map it to the desired range, and use math.floor () to make it an integer.

const randomIntegerInRange = (min, max) = > Math.floor(Math.random() * (max - min + 1)) + min;
// randomIntegerInRange(0, 5) -> 2
Copy the code

☝ Back to directory

randomNumberInRange

Returns a random number in the specified range.

Use math.random () to generate a random value and map it to the desired range using multiplication.

const randomNumberInRange = (min, max) = > Math.random() * (max - min) + min;
/ / randomNumberInRange (2, 10) - > 6.0211363285087005
Copy the code

☝ Back to directory

round

Rounds a number to the specified number of digits.

Round the number to the specified number using math.round () and template text. The second argument is omitted and Decimals is rounded to an integer.

const round = (n, decimals=0) = > Number(`The ${Math.round(`${n}e${decimals}`)}e-${decimals}`);
// round(1.005, 2) -> 1.01
Copy the code

☝ Back to directory

standardDeviation

Returns the standard deviation of a numeric array.

Use array.reduce () to calculate the mean, variance, and sum of the variances of the values, the variance of the values, and then determine the standard deviation. You can omit the second parameter to get the sample standard deviation, or set it to true to get the population standard deviation.

const standardDeviation = (arr, usePopulation = false) = > {
const mean = arr.reduce((acc, val) = > acc + val, 0) / arr.length;
return Math.sqrt(
arr.reduce((acc, val) = > acc.concat(Math.pow(val - mean, 2)), [])
.reduce((acc, val) = > acc + val, 0) / (arr.length - (usePopulation ? 0 : 1))); };// standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample)
// standardDeviation([10,2,38,23,38,23,21], true) -> 12.29899614287479 (population)
Copy the code

The media

☝ Back to directory

speechSynthesis

Perform speech synthesis (experiment).

Using SpeechSynthesisUtterance. Voice and window. SpeechSynthesis. GetVoices into voice mail (). Use Windows. SpeechSynthesis. Speak () broadcasting the news. Learn more about the SpeechSynthesisUtterance interface to the Web speech API.

const speechSynthesis = message= > {
const msg = new SpeechSynthesisUtterance(message);
msg.voice = window.speechSynthesis.getVoices()[0];
window.speechSynthesis.speak(msg);
};
// speechSynthesis('Hello, World') -> plays the message
Copy the code

node

☝ Back to directory

JSONToFile

Write the JSON object to a file.

Write a JSON object to a.json file using fs.writefile (), template text, and json.stringify ().

const fs = require('fs');
const JSONToFile = (obj, filename) = > fs.writeFile(`${filename}.json`.JSON.stringify(obj, null.2))
// JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
Copy the code

☝ Back to directory

readFileLines

Returns an array of rows in the specified file.

Buffers can be created from files using the readFileSync function in the FS node package. Converts the buffer to a string using the toString(encoding) function. Create arrays (per \n) from file contents by spliting file contents lines.

const fs = require('fs');
const readFileLines = filename= > fs.readFileSync(filename).toString('UTF8').split('\n');
/* contents of test.txt : line1 line2 line3 ___________________________ let arr = readFileLines('test.txt') console.log(arr) // -> ['line1', 'line2', 'line3'] */
Copy the code

object

☝ Back to directory

cleanObj

Removes any attributes other than those specified from the JSON object.

Keys () can be used to iterate over a given JSON Object and delete keys that are not included in the given array. In addition, if it is given a special key (childIndicator), it will search through it and apply the function to the inner object.

const cleanObj = (obj, keysToKeep = [], childIndicator) = > {
Object.keys(obj).forEach(key= > {
if (key === childIndicator) {
cleanObj(obj[key], keysToKeep, childIndicator);
} else if(! keysToKeep.includes(key)) {deleteobj[key]; }})}/* const testObj = {a: 1, b: 2, children: {a: 1, b: 2}} cleanObj(testObj, ["a"],"children") console.log(testObj)// { a: 1, children : { a: 1}} */
Copy the code

☝ Back to directory

objectFromPairs

Creates an object from the given key-value pair.

Create and combine key-value pairs using array.reduce ().

const objectFromPairs = arr= > arr.reduce((a, v) = > (a[v[0]] = v[1], a), {});
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
Copy the code

☝ Back to directory

objectToPairs

Creates an array of key-value pairs from an object.

Use object.keys () and array.map () to loop through an Object’s keys and generate an Array of key-value pairs.

const objectToPairs = obj= > Object.keys(obj).map(k= > [k, obj[k]]);
// objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]])
Copy the code

☝ Back to directory

shallowClone

Create a shallow clone of an object.

Create the original shallow clone using object.assign () and an empty Object ({}).

const shallowClone = obj= > Object.assign({}, obj);
/*
const a = { x: true, y: 1 };
const b = shallowClone(a);
a === b -> false
*/
Copy the code

☝ Back to directory

truthCheckCollection

Check that the predicate (second argument) is truthy for all elements of the set (first argument).

Use array.every () to check that each passed object has the specified property and returns a truthy value.

truthCheckCollection = (collection, pre) = > (collection.every(obj= > obj[pre]));
// truthCheckCollection([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}], "sex") -> true
Copy the code

string

☝ Back to directory

anagrams

Generates all the anagrams of the string (including duplicates).

Use recursion. For each letter in a given string, create all part puzzles for the rest of its letters. Combine the letters with each partial anagram using array.map (), and then combine all the anagrams with array.reduce () in an Array. The basic case is that the length of the string is equal to 2 or 1.

const anagrams = str= > {
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str.split(' ').reduce((acc, letter, i) = >
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val= > letter + val)), []);
};
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
Copy the code

☝ Back to directory

Capitalize

Capitalize the first letter of the string.

Use destructuring and toUpperCase() to set the first letter,… Rest is used to get an Array of characters after the first letter, followed by array.join (” “) to make it a string. Omit the lowerRest argument to leave the rest of the string unchanged, or set it to true to convert to lowercase.

const capitalize = ([first,...rest], lowerRest = false) = >
first.toUpperCase() + (lowerRest ? rest.join(' ').toLowerCase() : rest.join(' '));
// capitalize('myName') -> 'MyName'
// capitalize('myName', true) -> 'Myname'
Copy the code

☝ Back to directory

capitalizeEveryWord

Capitalize the first letter of each word in the string.

Use replace() to match each word and the first character of toUpperCase() to capitalize it.

const capitalizeEveryWord = str= > str.replace(/\b[a-z]/g.char= > char.toUpperCase());
// capitalizeEveryWord('hello world! ') -> 'Hello World! '
Copy the code

☝ Back to directory

escapeRegExp

Escape the string to be used in the regular expression.

Use replace() to escape special characters.

const escapeRegExp = str= > str.replace(/[.*+?^${}()|[\]\\]/g.'\ \ $&');
// escapeRegExp('(test)') -> \\(test\\)
Copy the code

☝ Back to directory

fromCamelCase

Converts strings from matches.

Use replace() to remove underscores, hyphens, and Spaces and convert words to matches. Omit the second argument to use the default delimiter _.

const fromCamelCase = (str, separator = '_') = >
str.replace(/([a-z\d])([A-Z])/g.'$1' + separator + '$2')
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g.'$1' + separator + '$2').toLowerCase();
// fromCamelCase('someDatabaseFieldName', ' ') -> 'some database field name'
// fromCamelCase('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized'
// fromCamelCase('someJavascriptProperty', '_') -> 'some_javascript_property'
Copy the code

☝ Back to directory

reverseString

Invert the string.

Use Array destructuring and array.reverse () to reverse the order of characters in the string. Use join(“) to combine characters to get a string.

const reverseString = str= > [...str].reverse().join(' ');
// reverseString('foobar') -> 'raboof'
Copy the code

☝ Back to directory

sortCharactersInString

Sort characters in a string alphabetically.

Use split(“) and array.sort () to recombine with localeCompare() to use join(“).

const sortCharactersInString = str= >
str.split(' ').sort((a, b) = > a.localeCompare(b)).join(' ');
// sortCharactersInString('cabbage') -> 'aabbceg'
Copy the code

☝ Back to directory

toCamelCase

Converts a string to a match.

Use replace() to remove underscores, hyphens, and Spaces and convert words to matches.

const toCamelCase = str= >
str.replace(/^([A-Z])|[\s-_]+(\w)/g.(match, p1, p2, offset) = >  p2 ? p2.toUpperCase() : p1.toLowerCase());
// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty'
// toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'
Copy the code

☝ Back to directory

truncateString

Truncates a string to a specified length.

Determines whether the length of the string is greater than num. Return the truncated string to the desired length and place… Appends to the end or original string.

const truncateString = (str, num) = >
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '... ' : str;
// truncateString('boomerang', 7) -> 'boom... '
Copy the code

practical

☝ Back to directory

coalesce

Returns the first non-empty/undefined parameter.

Use array.find () to return the first non-null /undefined argument.

const coalesce = (. args) = > args.find(_= >! [undefined.null].includes(_))
// coalesce(null,undefined,"",NaN, "Waldo") -> ""
Copy the code

☝ Back to directory

coalesceFactory

Returns a custom union function that returns the first argument that returns true from the supplied argument validation function.

Use array.find () to return the first argument that returns true from the supplied argument validation function.

const coalesceFactory = valid= > (. args) = > args.find(valid);
// const customCoalesce = coalesceFactory(_ => ! [null, undefined, "", NaN].includes(_))
// customCoalesce(undefined, null, NaN, "", "Waldo") //-> "Waldo"
Copy the code

☝ Back to directory

extendHex

Expand the 3-bit color code to 6-bit color code.

Use array.map (), split(), and array.join () to join the mapped Array to convert 3-bit RGB notated hexadecimal color-code to 6-bit numeric form. Array.slice() is used to remove # from string boot as it is added once.

const extendHex = shortHex= >
The '#' + shortHex.slice(shortHex.startsWith(The '#')?1 : 0).split(' ').map(x= > x+x).join(' ')
// extendHex('#03f') -> '#0033ff'
// extendHex('05a') -> '#0055aa'
Copy the code

☝ Back to directory

gettype

The native type of the return value.

If the value is undefined or null, return the constructor name in lower case, “undefined”, or “NULL”

const getType = v= >
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
// getType(new Set([1,2,3])) -> Set
Copy the code

☝ Back to directory

hexToRGB

Convert colorCode to RGB () string.

Converts a hexadecimal color code (prefixed with #) to a string with RGB values using the bitwise right operator and the mask bit &(and) operator. If it is a 3-digit Colorcode, then the 6-digit colorcode extended with extendHex () function (ref.extendHEX code snippet) does the same

const hexToRgb = hex= > {
const extendHex = shortHex= >
The '#' + shortHex.slice(shortHex.startsWith(The '#')?1 : 0).split(' ').map(x= > x+x).join(' ');
const extendedHex = hex.slice(hex.startsWith(The '#')?1 : 0).length === 3 ? extendHex(hex) : hex;
return `rgb(The ${parseInt(extendedHex.slice(1), 16) > >16}.The ${(parseInt(extendedHex.slice(1), 16) & 0x00ff00) > >8}.The ${parseInt(extendedHex.slice(1), 16) & 0x0000ff}) `;
}
// hexToRgb('#27ae60') -> 'rgb(39, 174, 96)'
// hexToRgb('#acd') -> 'rgb(170, 204, 221)'
Copy the code

☝ Back to directory

isArray

Checks whether the given argument is an array.

Use array.isarray () to check whether a value is an Array.

const isArray = val= >!!!!! val &&Array.isArray(val);
// isArray(null) -> false
// isArray([1]) -> true
Copy the code

☝ Back to directory

isBoolean

Checks whether the given argument is a native Boolean element.

Use Typeof to check whether a value is classified as a Boolean primitive.

const isBoolean = val= > typeof val === 'boolean';
// isBoolean(null) -> false
// isBoolean(false) -> true
Copy the code

☝ Back to directory

isFunction

Checks whether the given argument is a function.

Use Typeof to check whether a value is classified as a function primitive.

const isFunction = val= > val && typeof val === 'function';
// isFunction('x') -> false
// isFunction(x => x) -> true
Copy the code

☝ Back to directory

isNumber

Checks whether the given argument is a number.

Use Typeof to check whether a value is classified as a numeric primitive.

const isNumber = val= > typeof val === 'number';
// isNumber('1') -> false
// isNumber(1) -> true
Copy the code

☝ Back to directory

isString

Checks whether the given argument is a string.

Use Typeof to check whether a value is a string primitive.

const isString = val= > typeof val === 'string';
// isString(10) -> false
// isString('10') -> true
Copy the code

☝ Back to directory

isSymbol

Checks whether the given argument is a sign.

Use Typeof to check whether a value is classified as a symbolic primitive.

const isSymbol = val= > typeof val === 'symbol';
// isSymbol('x') -> false
// isSymbol(Symbol('x')) -> true
Copy the code

☝ Back to directory

RGBToHex

Convert the RGB component value to Colorcode.

Convert the given RGB argument to a hexadecimal string using the bit-to-left shift operator (<<) and toString(16), and then padStart(6,’0′) to get a six-bit hexadecimal value.

const RGBToHex = (r, g, b) = > ((r << 16) + (g << 8) + b).toString(16).padStart(6.'0');
// RGBToHex(255, 165, 1) -> 'ffa501'
Copy the code

☝ Back to directory

timeTaken

Measure the time it takes to execute a function.

Use console.time() and console.timeend () to measure the difference between the start and end times to determine how long the callback took to execute.

const timeTaken = callback= > {
console.time('timeTaken');  const r = callback();
console.timeEnd('timeTaken');  return r;
};
// timeTaken(() => Math.pow(2, 10)) -> 1024
/ / (logged) : timeTaken: 0.02099609375 ms
Copy the code

☝ Back to directory

toOrdinalSuffix

Add the ordinal suffix to the number.

Use the modular operator (%) to find values for single and tens digits. Finds the matching ordinal pattern number. If you find a number in teen mode, use teen serial number.

const toOrdinalSuffix = num= > {
const int = parseInt(num), digits = [(int % 10), (int % 100)],
ordinals = ['st'.'nd'.'rd'.'th'], oPattern = [1.2.3.4],
tPattern = [11.12.13.14.15.16.17.18.19];
return oPattern.includes(digits[0]) && !tPattern.includes(digits[1])? int + ordinals[digits[0] - 1] : int + ordinals[3];
};
// toOrdinalSuffix("123") -> "123rd"
Copy the code

☝ Back to directory

UUIDGenerator

UUID generated.

UUID generation using cryptoAPI, compliant with RFC4122 version 4.

const UUIDGenerator = () = >
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g.c= >
(c ^ crypto.getRandomValues(new Uint8Array(1))0] & 15 >> c / 4).toString(16));// UUIDGenerator() -> '7982fcfe-5721-4632-bede-6000885be57d'
Copy the code

☝ Back to directory

validateEmail

Returns true if the given string is a valid email, false otherwise.

Use regular expressions to check whether the E-mail message is valid. Return true if the email is valid, false if it is not.

const validateEmail = str= >
  /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,; : \ s @ "] +) *) | (" + ")) @ ((\ [[0-9] {1, 3} \. [0-9] {1, 3} \. [0-9] {1, 3} \. [0-9] {1, 3} \]) | ((\ [a zA - Z - 0-9] + \.) +[a-zA-Z]{2,}))$/.test(str);
// validateEmail([email protected]) -> true
Copy the code

☝ Back to directory

validateNumber

Returns true if the given value is a number, false otherwise.

Will be! IsNaN is used in conjunction with parseFloat() to check if the argument is numeric. Use isFinite() to check if the number isFinite. Use Number() to check whether the force is held.

const validateNumber = n= > !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
// validateNumber('10') -> true
Copy the code

Project address: github.com/dragonir/ut… (Updated continuously…)