Skip to content

Instantly share code, notes, and snippets.

@jkirira
Last active July 20, 2025 15:27
Show Gist options
  • Select an option

  • Save jkirira/6b60f2f15ae33a380758f5492ccd91f4 to your computer and use it in GitHub Desktop.

Select an option

Save jkirira/6b60f2f15ae33a380758f5492ccd91f4 to your computer and use it in GitHub Desktop.
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