@@ -5,6 +5,45 @@ import _ from "lodash";
55// #region Private Methods
66// -----------------------------------------------------------------------------------------
77
8+ /**
9+ * Transforms an enum into an array of its values
10+ *
11+ * @example
12+ * const roleTypes = TestUtils.enumToArray<RoleType>(RoleType);
13+ * // Returns [0, 1, 2, 3, 4, 5]
14+ * @template TEnum The enum to be transformed
15+ * @param {* } enumObject The enum to be transformed (cannot be typed to TEnum, or TS will return 'typeof TEnum'
16+ * instead of a value of TEnum)
17+ * @returns {TEnum[] }
18+ */
19+ const _enumToArray = < TEnum = any > ( enumObject : any ) : TEnum [ ] =>
20+ _objectToArray ( _numericEnumToPojo ( enumObject ) ) as TEnum [ ] ;
21+
22+ /**
23+ * Returns a random enum value from its type
24+ *
25+ * @example
26+ * const randomRoleType = TestUtils.getRandomEnum<RoleType>(RoleType);
27+ * // Might return the value '1', which is the value of RoleType.Team
28+ * @template TEnum The enum to be transformed
29+ * @param {* } enumObject The enum to be transformed (cannot be typed to TEnum, or TS will return 'typeof TEnum'
30+ * instead of a value of TEnum)
31+ * @param {TEnum } [excludeElement] A specific enum value to be excluded from the random selection.
32+ * @returns {TEnum }
33+ */
34+ const _getRandomEnum = < TEnum = any > (
35+ enumObject : any ,
36+ excludeElement ?: TEnum
37+ ) : TEnum => {
38+ let enumValues = _enumToArray ( enumObject ) ;
39+
40+ if ( excludeElement != null ) {
41+ enumValues = enumValues . filter ( ( e : any ) => e !== excludeElement ) ;
42+ }
43+
44+ return enumValues [ Math . floor ( Math . random ( ) * enumValues . length ) ] ;
45+ } ;
46+
847const _numericEnumToPojo = ( enumObject : any ) : { } => {
948 let pojo : { [ k : string ] : any } = { } ;
1049
@@ -87,6 +126,8 @@ const _timer = (name: string) => {
87126export const CoreUtils = {
88127 bindAll : _ . bindAll ,
89128 curry : _ . curry ,
129+ enumToArray : _enumToArray ,
130+ getRandomEnum : _getRandomEnum ,
90131 memoize : _ . memoize ,
91132 numericEnumToPojo : _numericEnumToPojo ,
92133 objectToArray : _objectToArray ,
0 commit comments