Last active
July 20, 2025 15:27
-
-
Save jkirira/6b60f2f15ae33a380758f5492ccd91f4 to your computer and use it in GitHub Desktop.
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
| const randomElement = <T>(xs: T[]): T => { | |
| const randomIndex = Math.floor(Math.random() * xs.length) | |
| return xs[randomIndex] | |
| } | |
| // Example usage | |
| const a = randomElement(['a', 'b', 'c']) | |
| //The values in the array don't have to be the same type. Typescript can infer. | |
| const b = randomElement([1, '2', 3, 4, {id: '1', foo: 'bar'}]) | |
| // using two different generic types | |
| const randomElement2 = <T, U>(xs: T[], ys: U[]): T | U => { | |
| const randomIndex = Math.floor(Math.random() * xs.length) | |
| const useX = Math.random() < 0.5 | |
| return useX ? xs[randomIndex] : ys[randomIndex] | |
| } | |
| // Example usage | |
| const c = randomElement2(['a', 'b', 'c'], [1, 2, 3]) ) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment