[30 seconds a knowledge point] Adapter

  adapter, array, es6, Front end, javascript

This series is translated from open source projects.30-seconds-of-code

This is a very excellent series, and the article summarizes a lot of usage.es6The code modules realized by grammar are not really understandable in 30 seconds, but also need your serious consideration. Some of them are very subtle and worth reading.

This article is in mygithubSynchronizing the updates, you can see the entire series of current translations.

If you have different or better opinions on this issue, please comment below. Please comment if you like. Thank you for reading.

ary

Create a function that can receive n parameters, ignoring other additional parameters.

Call the provided functionfn, the maximum number of parameters is n, useArray.prototype.slice(0,n)And expand operators (...)。

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));

Example

const firstTwoMax = ary(Math.max, 2);
[[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x));  // [6, 8, 10]

call

Given a key and a set of parameters, they are called when given a context. Mainly used for merger.

Use closures to call the value corresponding to key in the context, that is, the function with stored parameters.

const call = (key, ...args) => context => context[key](...args);

Example

Promise.resolve([1, 2, 3])
.then(call('map', x => 2 * x))
.then(console.log);  // [ 2, 4, 6 ]
const map = call.bind(null, 'map');
Promise.resolve([1, 2, 3])
.then(map(x => 2 * x))
.then(console.log);  // [ 2, 4, 6 ]

collectInto

Change a function that receives array parameters to a function with variable parameters.

Given a function, it returns a closure that collects all inputs into an array acceptance function.

const collectInto = fn => (...args) => fn(args);

Example

const Pall = collectInto(Promise.all.bind(Promise));
 let p1 = Promise.resolve(1);
 let p2 = Promise.resolve(2);
 let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
 Pall(p1, p2, p3).then(console.log);  // [1, 2, 3] (after about 2 seconds)

flip

Flip takes a function as a parameter, and then takes the first parameter as the last parameter.

Returns the closure of a variable parameter. Before applying other parameters, take other parameters other than the first as the first parameter.

const flip = fn => (first, ...rest) => fn(...rest, first);

Example

let a = { name: 'John Smith' };
let b = {};
const mergeFrom = flip(Object.assign);
let mergePerson = mergeFrom.bind(null, a);
mergePerson(b);  // == b
b = {};
Object.assign(b, a);  // == b

over

Create a function that can call every function that is passed in and has parameters, and then return the result.

UseArray.prototype.map()AndFunction.prototype.apply()Applies each function to a given parameter.

const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));

Example

const minMax = over(Math.min, Math.max);
 minMax(1, 2, 3, 4, 5);  // [1,5]

overArgs

Create a function that can call the function of the supplied converted parameter.

UseArray.prototype.map()willtransformsApply toargs, combined with extension operators (Pass the converted parameters to thefn.

const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));

Example

const square = n => n * n;
 const double = n => n * 2;
 const fn = overArgs((x, y) => [x, y], [square, double]);
 fn(9, 3);  // [81, 6]

pipeAsyncFunctions

Performs function combinations from left to right for asynchronous functions.

In the extension operator () is used in theArray.prototype.reduce()To usePromise.then()Performs a function combination from left to right.
These functions can return simple values,PromiseThe combination of, can also be defined as throughawaitReturnedasyncValue.
All functions must be unary.

const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));

Example

const sum = pipeAsyncFunctions(
x => x + 1,
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
x => x + 3,
async x => (await x) + 4
);
(async() => {
console.log(await sum(5));  // 15 (after one second)
})();

pipeFunctions

Performs a function combination from left to right.

After expanding the operator () is used in theArray.prototype.reduce()To perform a function combination from left to right.
The first (leftmost) function can accept one or more parameters; The remaining functions must be unary.

const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));

Example

const add5 = x => x + 5;
const multiply = (x, y) => x * y;
const multiplyAndAdd5 = pipeFunctions(multiply, add5);
multiplyAndAdd5(5, 2);  // 15

promisify

Converts an asynchronous function to a that returns promise.

Use local apply to return a function that returns a that calls the original functionPromise.
practical...Operator to pass in all parameters.

const promisify = func => (...args) =>
new Promise((resolve, reject) =>
func(...args, (err, result) => (err ?  reject(err) : resolve(result)))
);

Example

const delay = promisify((d, cb) => setTimeout(cb, d));
delay(2000).then(() => console.log('Hi!'  ));  // Promise resolves after 2s

rearg

Creates a function that calls the provided function, whose parameters are arranged according to the specified index.

utilizeArray.prototype.map()According toindexesAnd expand operators (...Reorder the parameters and pass the converted parameters to thefn.

const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));

Example

var rearged = rearg(
function(a, b, c) {
return [a, b, c];
},
[2, 0, 1]
);
rearged('b', 'c', 'a');  // ['a', 'b', 'c']

spreadOver

Accepts a variable parameter function and returns a closure that accepts an array of parameters to map to the function’s input.

Using closures and extension operators (Map an array of parameters to the input of the function.

const spreadOver = fn => argsArr => fn(...argsArr);

Example

const arrayMax = spreadOver(Math.max);
 arrayMax([1, 2, 3]);  // 3

unary

Create a function that accepts at most one parameter, ignoring any other parameters.

Only the first parameter is passed to the function to be calledfn.

const unary = fn => val => fn(val);

Example

['6', '8', '10'].map(unary(parseInt));  // [6, 8, 10]

Recommended reading