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 ] @@ -890,6 +890,25 @@ Foo.prototype: { user: 'pebbles', age: 1 } }; mapValues(users, u => u.age); // { fred: 40, pebbles: 1 } +merge
Creates a new object from the combination of two or more objects.
Use
Array.reduce()combined withObject.keys(obj)to iterate over all objects and keys. UsehasOwnProperty()andArray.concat()to append values for keys existing in multiple objects.const merge = (...objs) => + [...objs].reduce( + (acc, obj) => + Object.keys(obj).reduce((a, k) => { + acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k]; + return acc; + }, {}), + {} + ); +const object = { + a: [{ x: 2 }, { y: 4 }], + b: 1 +}; +const other = { + a: { z: 3 }, + b: [2, 3], + c: 'foo' +}; +merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }objectFromPairs
Creates an object from the given key-value pairs.
Use
Array.reduce()to create and combine key-value pairs.const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {});objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}objectToPairs
Creates an array of key-value pair arrays from an object.
Use
Object.keys()andArray.map()to iterate over the object's keys and produce an array with key-value pairs.const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); diff --git a/snippets/merge.md b/snippets/merge.md index fbc4ec7b7..b20d05253 100644 --- a/snippets/merge.md +++ b/snippets/merge.md @@ -10,9 +10,7 @@ const merge = (...objs) => [...objs].reduce( (acc, obj) => Object.keys(obj).reduce((a, k) => { - acc[k] = acc.hasOwnProperty(k) - ? [].concat(acc[k]).concat(obj[k]) - : obj[k]; + acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k]; return acc; }, {}), {} @@ -22,12 +20,12 @@ const merge = (...objs) => ```js const object = { a: [{ x: 2 }, { y: 4 }], - b: 1, + b: 1 }; const other = { a: { z: 3 }, b: [2, 3], - c: 'foo', + c: 'foo' }; merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' } ```