Last active
January 15, 2019 10:58
-
-
Save Akiyamka/e3c289e87eb43a2c37bb01cec498761a to your computer and use it in GitHub Desktop.
Weight equalizer (repl: https://repl.it/@alieksandrdubinin/Equalizer)
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 data = | |
[ | |
{ | |
"val": 30, | |
"children": [ | |
{ | |
"val": 123, | |
"children": [ | |
{ | |
"val": 0.2, | |
}, | |
{ | |
"val": 0.56, | |
}, | |
{ | |
"val": 0.21, | |
}, | |
] | |
}, | |
{ | |
"val": 456, | |
"children": [ | |
{ | |
"val": 123124, | |
}, | |
{ | |
"val": 412231, | |
}, | |
{ | |
"val": 640283, | |
}, | |
] | |
}, | |
{ | |
"val": 789, | |
"children": [ | |
{ | |
"val": 2, | |
}, | |
{ | |
"val": 3, | |
}, | |
{ | |
"val": 7, | |
}, | |
] | |
} | |
] | |
} | |
]; |
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
import data from './dataset.json'; | |
/** | |
* Weight equalizer | |
*/ | |
function Equalizer(setup = {}) { | |
const options = { | |
val: 'val', | |
children: 'children', | |
weight: 'weight', | |
maxDeep: 100, | |
...setup | |
}; | |
function getWeights(parent, _deep = 0) { | |
if (!parent[options.children]) return parent; | |
const summ = parent[options.children].reduce((s, c) => s + (c[options.weight] || c[options.val]), 0); | |
parent[options.children].forEach(child => { | |
child[options.weight] = parent[options.val] * child[options.val] / summ; | |
if (_deep >= options.maxDeep) { | |
console.warn(`[Equalizer]: Max deep reached (${options.maxDeep});`); | |
return; | |
} | |
if (child[options.children]) getWeights(child, _deep + 1); | |
}); | |
return parent | |
} | |
return parent => getWeights(parent, 0); | |
} | |
const equalizer = Equalizer(); | |
equalizer(data[0]); | |
console.log(data[0]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment