All files / src replacer.ts

100% Statements 15/15
100% Branches 10/10
100% Functions 4/4
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            633x     4x 28x 20x         146x 139x     7x 2x     5x 2x     3x 2x     1x    
export type ReplacerMethod = (value: any) => any;
 
export type MapEntries<K, V> = readonly (readonly [K, V])[];
 
export type ReplacerType = ReplacerMethod | Map<any, any> | MapEntries<any, any>;
 
export const defaultReplacer: ReplacerMethod = (value) => value;
 
export function replacerFromTable(table: Map<any, any>): ReplacerMethod {
	return (value) => {
		if (table.has(value)) return table.get(value);
		return value;
	};
}
 
export function getReplacer(replacerOption: ReplacerType | undefined): ReplacerMethod {
	if (!replacerOption) {
		return defaultReplacer;
	}
 
	if (typeof replacerOption === 'function') {
		return replacerOption;
	}
 
	if (replacerOption instanceof Map) {
		return replacerFromTable(replacerOption);
	}
 
	if (Array.isArray(replacerOption)) {
		return replacerFromTable(new Map(replacerOption));
	}
 
	throw 'Incorrect replacer type. It must be a function, a map, or entries.';
}