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); @@ -1427,14 +1427,14 @@ Foo.prototype}; const autoPluralize = pluralize(PLURALS); autoPluralize(2, 'person'); // 'people' +removeNonASCII
Removes non-printable ASCII characters.
Use a regular expression to remove non-printable ASCII characters.
const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); +removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum'reverseString
Reverses a string.
Use the spread operator (
...) andArray.reverse()to reverse the order of the characters in the string. Combine characters to get a string usingString.join('').const reverseString = str => [...str].reverse().join('');reverseString('foobar'); // 'raboof'sortCharactersInString
Alphabetically sorts the characters in a string.
Use the spread operator (
...),Array.sort()andString.localeCompare()to sort the characters instr, recombine usingString.join('').const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');sortCharactersInString('cabbage'); // 'aabbceg'splitLines
Splits a multiline string into an array of lines.
Use
String.split()and a regular expression to match line breaks and create an array.const splitLines = str => str.split(/\r?\n/);splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , ''] -stripHTMLTags
Removes HTML/XML tags from string.
Use a regular expression to remove HTML/XML tags from a string.
const stripHTMLTags = str => str.replace(/<[^>]*>/g, ''); -stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'toCamelCase
Converts a string to camelcase.
Break the string into words and combine them capitalizing the first letter of each word, using a regexp.
const toCamelCase = str => { let s = str && @@ -1766,4 +1766,6 @@ Logs: { yesNo('yes'); // true yesNo('No'); // false yesNo('Foo', true); // true -