Last active
September 19, 2017 18:56
-
-
Save sasajib/8b37c9678ffd3a4752e997d1c7704933 to your computer and use it in GitHub Desktop.
Javascript Utils
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
//[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