File size: 1,444 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import type { ExperimentAssignment } from '../types';
export function isObject( x: unknown ): x is Record< string, unknown > {
return typeof x === 'object' && x !== null;
}
/**
* Test if a piece of data is a valid name
* @param name The data to test
*/
export function isName( name: unknown ): name is string {
return typeof name === 'string' && name !== '' && /^[a-z0-9_]*$/.test( name );
}
/**
* Test if a piece of data is a valid experimentAssignment
* @param experimentAssignment The data to test
*/
export function isExperimentAssignment(
experimentAssignment: unknown
): experimentAssignment is ExperimentAssignment {
return (
isObject( experimentAssignment ) &&
isName( experimentAssignment[ 'experimentName' ] ) &&
( isName( experimentAssignment[ 'variationName' ] ) ||
experimentAssignment[ 'variationName' ] === null ) &&
typeof experimentAssignment[ 'retrievedTimestamp' ] === 'number' &&
typeof experimentAssignment[ 'ttl' ] === 'number' &&
experimentAssignment[ 'ttl' ] !== 0
);
}
/**
* Basic validation of ExperimentAssignment
* Throws if invalid, returns the experimentAssignment if valid.
* @param experimentAssignment The data to validate
*/
export function validateExperimentAssignment(
experimentAssignment: unknown
): ExperimentAssignment {
if ( ! isExperimentAssignment( experimentAssignment ) ) {
throw new Error( 'Invalid ExperimentAssignment' );
}
return experimentAssignment;
}
|