-
-
Save lahmatiy/159624a61568930fa06f5bb6f91ccad1 to your computer and use it in GitHub Desktop.
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
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