Skip to content

Instantly share code, notes, and snippets.

@i-am-tom
Last active October 16, 2016 18:40
Show Gist options
  • Save i-am-tom/eb9283f8b4b3fd1852df77eb3405b0fe to your computer and use it in GitHub Desktop.
Save i-am-tom/eb9283f8b4b3fd1852df77eb3405b0fe to your computer and use it in GitHub Desktop.
Merging records (with history) using an array scan.
// 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