Skip to content

Instantly share code, notes, and snippets.

@robbywashere-zz
Created November 8, 2017 21:38
Show Gist options
  • Save robbywashere-zz/d0f0feb265c5ca3aec31ba2001ddb73c to your computer and use it in GitHub Desktop.
Save robbywashere-zz/d0f0feb265c5ca3aec31ba2001ddb73c to your computer and use it in GitHub Desktop.
import map from 'lodash/map';
import Promise from 'bluebird';
function isNode({ key, type, linkType } = {}) {
return (key === 'sys' && type === 'Link' && (linkType === 'Entry' || linkType === 'Asset'));
}
// TODO: combine these somehow
function walk(node, FN, depth = 10, mapper = map) {
if (typeof node !== 'object' || depth === 0) return;
return mapper(Object.entries(node), ([key, values]) => {
if (values === null) return;
if (isNode({ ...values, key })) {
return walk(FN(node), FN, depth - 1, mapper);
}
return walk(values, FN, depth, mapper);
});
}
function walkAsync(node, FN, depth = 10, mapper = Promise.map) {
if (typeof node !== 'object' || depth === 0) return;
return mapper(Object.entries(node), async ([key, values]) => {
if (values === null) return;
if (isNode({ ...values, key })) {
return walkAsync(await FN(node), FN, depth - 1, mapper);
}
return walkAsync(values, FN, depth, mapper);
});
}
export { walk, walkAsync };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment