Last active
May 10, 2022 00:05
-
-
Save snowden-fu/f942bbfb3680e800663b44d3923dd84f to your computer and use it in GitHub Desktop.
Utilities function for JavaScript
This file contains 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
/** | |
* | |
* @param {*} arr array to search | |
* @param {*} val single element to search in array | |
* @returns | |
*/ | |
function findAllIndexesOf(arr, val) { | |
var indexes = [], i; | |
for(i = 0; i < arr.length; i++) | |
if (arr[i] === val) | |
indexes.push(i); | |
return indexes; | |
} | |
/** | |
* e.g. | |
* | |
* arr = [ 'a', ' ', 'b', 'c', 'b' ] | |
* val = 'b' | |
* getAllIndexes(arr, val)-> [ 2, 4 ] | |
*/ |
This file contains 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
/** | |
* | |
* @param {number} length length of object | |
* @param {number} n length of index to generate | |
* @returns | |
*/ | |
const randIdxArrayByLength = (length, n)=>{ | |
const res = Array.from({length:n},(item, index)=> index).sort(() => Math.random() - 0.5).slice(0,n); | |
return res | |
} | |
// e.g. | |
// console.log(randIdxArrayByLength(5, 3)); | |
// [ 1, 0, 2 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment