Last active
August 17, 2016 14:26
-
-
Save kendru/594d8cf6f9a93b22e653f419e9b93daf to your computer and use it in GitHub Desktop.
Demonstrate re-indexing already-indexed data
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
const source = { | |
data: { | |
123: { | |
0: 15, | |
1: 1 | |
}, | |
456: { | |
0: 53, | |
1: 4 | |
} | |
}, | |
otherData: { | |
123: { | |
happy: true | |
}, | |
456: { | |
happy: false | |
} | |
} | |
}; | |
const dest = { | |
123: { | |
data: { | |
0: 15, | |
1: 1 | |
}, | |
otherData: { | |
happy: true | |
} | |
}, | |
456: { | |
data: { | |
0: 53, | |
1: 4 | |
}, | |
otherData: { | |
happy: false | |
} | |
} | |
}; | |
function normalize(obj, path = []) { | |
if (!_.isPlainObject(obj)) { | |
return [ path.concat([obj]) ]; | |
} | |
return _(Object.keys(obj)) | |
.map(k => normalize(obj[k], path.concat([k]))) | |
.flatten() | |
.value(); | |
} | |
function indexOn(coll, path) { | |
if (!path.length) { | |
return coll; | |
} | |
const [ prop, ...props ] = path; | |
const idx = coll.reduce((acc, elem) => { | |
const idxVal = elem[prop]; | |
if (acc[idxVal]) { | |
acc[idxVal].push(elem); | |
} else { | |
acc[idxVal] = [ elem ]; | |
} | |
return acc; | |
}, {}) | |
return _.mapValues(idx, elems => indexOn(elems, props)); | |
} | |
function record(names) { | |
return row => _.zipObject(names, row); | |
} | |
function walkLeaves(node, fn) { | |
if (_.isArray(node)) { | |
return fn(node[0]); | |
} | |
return _.mapValues(node, branch => walkLeaves(branch, fn)); | |
} | |
// Named Records | |
_.isEqual( | |
dest, | |
walkLeaves( | |
indexOn( | |
normalize(source).map(record(['selection', 'minutes', 'isConverted', 'count'])), | |
['minutes', 'selection', 'isConverted']), | |
r => r.count)) | |
// Column numbers | |
_.isEqual( | |
dest, | |
walkLeaves( | |
indexOn( | |
normalize(source), | |
[1, 0, 2]), | |
r => r[3])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment