Last active
March 20, 2019 22:40
-
-
Save david-mart/e045d46a887991b8e39da02f752da656 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 a = [0,[[2,[3,3]],[[3,[4,4]],[3,[4,[[6,6],5]]]]]] | |
const findBranchSize = R.pipe(R.flatten, R.length) | |
const compareBranches = R.useWith(R.gte, [findBranchSize, findBranchSize]) | |
const findDeepestNode = (tree) => { | |
let i = 0; | |
let path = []; | |
let currentBranch = tree | |
while((R.length(currentBranch[0]) || R.length(currentBranch[1]))) { | |
let deepestIndex = compareBranches(currentBranch[0], currentBranch[1]) ? 0 : 1; | |
path.push(deepestIndex) | |
currentBranch = currentBranch[deepestIndex] | |
i++ | |
} | |
return path | |
} | |
const data = [ | |
{ id: 1, size: 20 }, | |
[ | |
[ | |
{ id: 2, size: 19 }, | |
[ | |
[ | |
{ id: 3, size: 16 }, | |
[ | |
[ | |
{ id: 4, size: 5 }, | |
[ | |
[ | |
{ id: 5, size: 3 }, | |
[ | |
{ id: 6, size: 3 }, | |
[ | |
{ id: 7, size: 18 }, | |
{ id: 8, size: 17 } | |
] | |
] | |
], | |
{ id: 9, size: 12 } | |
] | |
], | |
[ | |
{ id: 13, size: 3 }, | |
[ | |
[ | |
{ id: 17, size: 3 }, | |
[ | |
{ id: 18, size: 3 }, | |
[ | |
{ id: 19, size: 18 }, | |
{ id: 20, size: 17 } | |
] | |
] | |
], | |
[ | |
{ id: 15, size: 18 }, | |
{ id: 16, size: 17 } | |
] | |
] | |
], | |
] | |
], | |
{ id: 11, size: 13 } | |
] | |
], | |
{ id: 12, size: 7 } | |
] | |
]; | |
const checkCluster = R.pipe(R.flatten, R.map(R.prop('size')), R.sum, R.gte(40)) | |
const splitTreeBranches = tree => { | |
const clusters = [] | |
let currentTree = tree; | |
let i = 0; | |
while(currentTree && (i < 5)) { | |
if (checkCluster([currentTree])) { | |
clusters.push(currentTree) | |
currentTree = null; | |
} else { | |
console.log(currentTree) | |
let path = findDeepestNode(currentTree) | |
let currentBranch = R.path(path)(currentTree) | |
let j = 0; | |
let lastPath, lastBranch; | |
while(checkCluster([currentBranch]) && j < 10) { | |
lastPath = path | |
lastBranch = currentBranch | |
path = R.init(path); | |
currentBranch = R.path(path)(currentTree) | |
} | |
clusters.push(flatten([lastBranch])) | |
currentTree = R.dissocPath(lastPath)(currentTree) | |
} | |
i++; | |
} | |
return clusters | |
} | |
splitTreeBranches(data) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment