Adapter
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); + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Adapter
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);Promise.resolve([1, 2, 3]) .then(call('map', x => 2 * x)) .then(console.log); //[ 2, 4, 6 ] @@ -1165,6 +1165,16 @@ Foo.prototype}[tag] || tag) );unescapeHTML('<a href="#">Me & you</a>'); // '<a href="#">Me & you</a>' +URLJoin
Joins all given URL segments together, then normalizes the resulting URL.
Use
String.join('/')to combine URL segments, then a series ofString.replace()calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with'&'and normalize first parameter delimiter).const URLJoin = (...args) => + args + .join('/') + .replace(/[\/]+/g, '/') + .replace(/^(.+):\//, '$1://') + .replace(/^file:/, 'file:/') + .replace(/\/(\?|&|#[^!])/g, '$1') + .replace(/\?/g, '&') + .replace('&', '?'); +URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'words
Converts a given string into an array of words.
Use
String.split()with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. UseArray.filter()to remove any empty strings. Omit the second argument to use the default regexp.const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);words('I love javaScript!!'); // ["I", "love", "javaScript"] words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"] diff --git a/snippets/URLJoin.md b/snippets/URLJoin.md index 67d921003..aa7492782 100644 --- a/snippets/URLJoin.md +++ b/snippets/URLJoin.md @@ -6,13 +6,14 @@ Use `String.join('/')` to combine URL segments, then a series of `String.replace ```js const URLJoin = (...args) => - args.join('/') - .replace(/[\/]+/g,'/') - .replace(/^(.+):\//,'$1://') - .replace(/^file:/,'file:/') - .replace(/\/(\?|&|#[^!])/g, '$1') - .replace(/\?/g,'&') - .replace('&','?'); + args + .join('/') + .replace(/[\/]+/g, '/') + .replace(/^(.+):\//, '$1://') + .replace(/^file:/, 'file:/') + .replace(/\/(\?|&|#[^!])/g, '$1') + .replace(/\?/g, '&') + .replace('&', '?'); ``` ```js