Skip to content

Instantly share code, notes, and snippets.

@Adesh

Adesh/randSplit.js

Created Jan 16, 2018
Embed
What would you like to do?
module.exports = randSplit;
function randSplit(_ary, _percentageSplit) {
// make sure the params are arrays
if(!Array.isArray(_ary) || !Array.isArray(_percentageSplit)) {
console.log(`Both arguments must be of array type`);
return false;
}
// indeed, logicaly this sum of percentage split should be 100
if(_percentageSplit.reduce((a, b) => a + b, 0) != 100) {
console.log(`Sum of elements of _percentageSplit must be 100, but is `,_percentageSplit.reduce((a, b) => a + b, 0).toString());
return false;
}
// because we don't want to modify the original array
_ary = JSON.parse(JSON.stringify(_ary));
// we will populate result object for response
let result = {};
let eleSplit = []
for (let i in _percentageSplit) {
let eleInThisAry = parseInt(_ary.length*_percentageSplit[i]/100);
console.log(`${eleInThisAry.toString()} (${_percentageSplit[i]}% of ${_ary.length}) elements in ${i} object`);
eleSplit.push(eleInThisAry);
}
for (let i in _percentageSplit) {
result[i] = [];
while(result[i].length != eleSplit[i]){
result[i].push(_ary.splice(Math.floor(Math.random()*_ary.length), 1)[0])
}
}
return result
};
/* TEST */
/*
let res1 = randSplit([1,2,3,4,5,6,7,8,9,10], [20,30,5]);
// should return false : sum of 2nd argument is not 100
console.log("res1:: ", res1);
let res2 = randSplit("[1,2,3,4,5,6,7,8,9,10]", [20,30,50]);
// should return false : first argument is not an array
console.log("res2:: ", res2);
let res3 = randSplit([1,2,3,4,5,6,7,8,9,10], [20,30,50]);
// should return proper response
console.log("res3:: ", res3);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment