Skip to content

Instantly share code, notes, and snippets.

@kendru
Last active August 17, 2016 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kendru/594d8cf6f9a93b22e653f419e9b93daf to your computer and use it in GitHub Desktop.
Save kendru/594d8cf6f9a93b22e653f419e9b93daf to your computer and use it in GitHub Desktop.
Demonstrate re-indexing already-indexed data
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