How to get a random item from an enumeration?
enum Colors {
Red, Green, Blue
}
function getRandomColor(): Color {
// return a random Color (Red, Green, Blue) here
}
After much inspiration from the other solutions, and the keyof keyword, here is a generic method that returns a typesafe random enum.
function randomEnum<T>(anEnum: T): T[keyof T] {
const enumValues = Object.keys(anEnum)
.map(n => Number.parseInt(n))
.filter(n => !Number.isNaN(n)) as unknown as T[keyof T][]
const randomIndex = Math.floor(Math.random() * enumValues.length)
const randomEnumValue = enumValues[randomIndex]
return randomEnumValue;
}
Use it like this:
interface MyEnum {X, Y, Z}
const myRandomValue = randomEnum(MyEnum)
myRandomValue will be of type MyEnum.
Most of the above answers are returning the enum keys, but don't we really care about the enum values?
If you are using lodash, this is actually as simple as:
_.sample(Object.values(myEnum)) as MyEnum
The casting is unfortunately necessary as this returns a type of any. :(
If you're not using lodash, or you want this as its own function, we can still get a type-safe random enum by modifying @Steven Spungin's answer to look like:
function randomEnum<T>(anEnum: T): T[keyof T] {
const enumValues = (Object.values(anEnum) as unknown) as T[keyof T][];
const randomIndex = Math.floor(Math.random() * enumValues.length);
return enumValues[randomIndex];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With