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); @@ -749,6 +749,14 @@ console.log< document.querySelector('#someElement').innerHTML = 'Hello'; longRunningFunction(); //Browser will not update the HTML until this has finished defer(longRunningFunction); // Browser will update the HTML then run the function +defer
Invokes the provided function after
waitmilliseconds.Use
setTimeout()to delay execution offn. Use the spread (...) operator to supply the function with an arbitrary number of arguments.const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); +delay( + function(text) { + console.log(text); + }, + 1000, + 'later' +); // Logs 'later' after one second.functionName
Logs the name of a function.
Use
console.debug()and thenameproperty of the passed method to log the method's name to thedebugchannel of the console.const functionName = fn => (console.debug(fn.name), fn);functionName(Math.max); // max (logged in debug channel of console)memoize
Returns the memoized (cached) function.
Create an empty cache by instantiating a new
Mapobject. Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. Thefunctionkeyword must be used in order to allow the memoized function to have itsthiscontext changed if necessary. Allow access to thecacheby setting it as a property on the returned function.const memoize = fn => { diff --git a/snippets/delay.md b/snippets/delay.md index 3735fa065..09f7c2606 100644 --- a/snippets/delay.md +++ b/snippets/delay.md @@ -10,7 +10,11 @@ const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); ``` ```js -delay(function(text) { - console.log(text); -}, 1000, 'later'); // Logs 'later' after one second. +delay( + function(text) { + console.log(text); + }, + 1000, + 'later' +); // Logs 'later' after one second. ```