Last active
October 16, 2016 18:40
-
-
Save i-am-tom/eb9283f8b4b3fd1852df77eb3405b0fe to your computer and use it in GitHub Desktop.
Merging records (with history) using an array scan.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// reduce with the acc at each stage. | |
const scan = (f, init, xs) => { | |
let acc = init | |
return [init, ... xs.map( | |
x => acc = f(acc, x) | |
)] | |
} | |
// Some methods... | |
const mine = (x, y) => x | |
const theirs = (x, y) => y | |
const both = (x, y) => [ x, y ] // We'll use as the default. | |
const concat = (x, y) => x.concat(y) | |
const scheme = | |
{ id: theirs | |
, name: mine | |
, likes: concat | |
} | |
const mergeWith = scheme => (xs, ys) => { | |
let result = {} | |
// Assuming same structures... | |
Object.keys(xs).map( | |
k => result[key] = | |
(scheme[k] || both) | |
(xs[k], ys[k]) | |
) | |
return result | |
} | |
const [ head, ... tail ] = | |
[ { id: 1 | |
, name: 'borb' | |
, likes: [ 'vuvuzela' ] | |
} | |
, { id: 3 | |
, name: 'robert' | |
, likes: [ 'bagels' ] | |
} | |
, { id: 5 | |
, likes: [ 'clarinet' ] | |
} | |
] | |
console.log(scan(mergeWith(scheme), head, tail)) | |
// [ { id: 1, name: 'borb', likes: [ 'vuvuzela' ] } | |
// , { id: 3, name: 'borb', likes: [ 'vuvuzela', 'bagels' ] } | |
// , { id: 5, name: 'borb', likes: [ 'vuvuzela', 'bagels', 'clarinet' ] } | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment