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); @@ -1630,6 +1630,11 @@ Foo.prototypeShow examplesmask(1234567890); // '******7890' mask(1234567890, 3); // '*******890' mask(1234567890, -4, '$'); // '$$$$567890' +pad
Pads a string on both sides with the specified character, if it's shorter than the specified length.
Use
String.padStart()andString.padEnd()to pad both sides of the given string. Omit the third argument,char, to use the whitespace character as the default padding character.const pad = (str, length, char = ' ') => + str.padStart((str.length + length) / 2, char).padEnd(length, char); +pad('cat', 8); // ' cat ' +pad(String(42), 6, '0'); // '004200' +pad('foobar', 3); // 'foobar'palindrome
Returns
trueif the given string is a palindrome,falseotherwise.Convert string
String.toLowerCase()and useString.replace()to remove non-alphanumeric characters from it. Then,String.split('')into individual characters,Array.reverse(),String.join('')and compare to the original, unreversed string, after converting itString.tolowerCase().const palindrome = str => { const s = str.toLowerCase().replace(/[\W_]/g, ''); return (