Skip to content

Instantly share code, notes, and snippets.

@lahmatiy
Created November 16, 2019 17:40
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 lahmatiy/159624a61568930fa06f5bb6f91ccad1 to your computer and use it in GitHub Desktop.
Save lahmatiy/159624a61568930fa06f5bb6f91ccad1 to your computer and use it in GitHub Desktop.
methods = {
tree_: function(current, getter, rootValue, makeLeaf = (item, children) => ({ item, children })) {
const scan = new Set(ensureArray(current));
const hasParent = new Set();
const leafs = new Map();
const fn = typeof getter === 'function'
? getter
: current => getPropertyValue(current, getter);
const isRootValue = typeof rootValue === 'function'
? rootValue
: rootValue === undefined
? value => value === undefined || value === null
: value => value === rootValue;
const vis = new Set();
const makeLeafs = item => {
if (vis.has(item)) { console.log('!!!', item); return; }
vis.add(item);
return makeLeaf(item, leafs.has(item) ? leafs.get(item).map(makeLeafs) : null);
};
// resolving
scan.forEach(item => {
const parent = fn(item);
if (leafs.has(parent)) {
leafs.get(parent).push(item);
} else {
leafs.set(parent, [item]);
}
if (parent !== item) {
hasParent.add(item);
if (!isRootValue(parent)) {
scan.add(parent);
}
}
});
// assembly
return [...leafs.keys()].filter(k => !hasParent.has(k)).map(makeLeafs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment