Skip to content

Instantly share code, notes, and snippets.

@sasajib
Last active September 19, 2017 18:56
Show Gist options
  • Save sasajib/8b37c9678ffd3a4752e997d1c7704933 to your computer and use it in GitHub Desktop.
Save sasajib/8b37c9678ffd3a4752e997d1c7704933 to your computer and use it in GitHub Desktop.
Javascript Utils
//[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17] => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17]]
function grouped(arr, limit){
return arr.map((data, index) => {
return index % limit === 0 ? arr.slice(index, index + limit) : null;
}).filter((item) => { return item; })
}
//range crete [0,1,2,3,4...number]
function range(number){
return Array.from(new Array(number), (x,i) => i)
}
//random int
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
/* Upsert Array of object*/
const upsertArray = (arr, predicate, value) => {
const indexed = arr.map((data, index) => {
return {...data, ...{index}};
});
const filtered = indexed.filter(predicate);
if(filtered.length){
let index = filtered[0].index;
arr[index] = value;
return arr;
}else {
return [...arr, ...[value]];
}
};
let j = [{id: 1, value: "Bangladesh"}, {id: 2, value: "Australia"}];
const predicate = d => d.id === 2;
const k = upsertArray(j, predicate, {id: 2, value: "Aus"});
console.log(k); //[{id: 1, value: "Bangladesh"}, {id: 2, value: "Aus"}];
************************************************************************
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment