Created
August 12, 2022 09:54
-
-
Save IlanFrumer/10af8d09ed259686935fb9f3829f346d to your computer and use it in GitHub Desktop.
Map an array to multiple values (fixed or random)
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
const randomize = (min: number, max: number) => | |
Math.floor(Math.random() * (max - min + 1)) + min; | |
export const mapMulti = (val1: number, val2?: number) => { | |
let iterator: () => unknown[]; | |
if (typeof val2 === "undefined") { | |
const arr = Array.from({ length: val1 }); | |
iterator = () => arr; | |
} else { | |
iterator = () => Array.from({ length: randomize(val1, val2) }); | |
} | |
return function <T, U>( | |
array: T[], | |
fn: (x: T, index: number, gIndex: number) => U | |
) { | |
const result: U[] = []; | |
array.forEach((x, gIndex) => { | |
iterator().forEach((_, index) => result.push(fn(x, index, gIndex))); | |
}); | |
return result; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment