Adapter
ary
Creates a function that accepts up to n arguments, ignoring any additional arguments.
Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).
const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Adapter
ary
Creates a function that accepts up to
narguments, ignoring any additional arguments.Call the provided function,
fn, with up tonarguments, usingArray.slice(0,n)and the spread operator (...).const ary = (fn, n) => (...args) => fn(...args.slice(0, n));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 arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
const call = (key, ...args) => context => context[key](...args); @@ -786,6 +786,18 @@ console.log< console.log(this, event); // document.body, MouseEvent }; document.body.addEventListener('click', once(startApp)); // only runs `startApp` once upon click +partial
Creates a function that invokes
fnwithpartialsprepended to the arguments it receives.Use the spread operator (
...) to prependpartialsto the list of arguments offn.const partial = (fn, ...partials) => (...args) => fn(...partials, ...args); +function greet(greeting, name) { + return greeting + ' ' + name + '!'; +} +const greetHello = partial(greet, 'Hello'); +greetHello('John'); // 'Hello John!' +partialRight
Creates a function that invokes
fnwithpartialsappended to the arguments it receives.Use the spread operator (
...) to appendpartialsto the list of arguments offn.const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials); +function greet(greeting, name) { + return greeting + ' ' + name + '!'; +} +const greetJohn = partialRight(greet, 'John'); +greetJohn('Hello'); // 'Hello John!'runPromisesInSeries
Runs an array of promises in series.
Use
Array.reduce()to create a promise chain, where each promise returns the next promise when resolved.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 diff --git a/snippets/partialRight.md b/snippets/partialRight.md index 6b6aa1131..d64f7f1d6 100644 --- a/snippets/partialRight.md +++ b/snippets/partialRight.md @@ -5,7 +5,7 @@ Creates a function that invokes `fn` with `partials` appended to the arguments i Use the spread operator (`...`) to append `partials` to the list of arguments of `fn`. ```js -const partialRight = (fn, ...partials) => (...args) => fn( ...args, ...partials); +const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials); ``` ```js