All files / src/helpers/validators alphabetValidator.js

100% Statements 9/9
100% Branches 6/6
100% Functions 1/1
100% Lines 9/9

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              6x 18x 4x     14x 14x 1x         13x 13x 1x      
/**
 * Validates a given alphabet to match the following conditions:
 * - alphabet is required
 * - contains only alphanumeric characters
 * - contains no duplicate characters
 * @param {string} alphabet
 */
export const alphabetValidator = (alphabet) => {
	if (!alphabet) {
		throw new Error("Missing required parameter: alphabet");
	}
 
	const illegal = alphabet.match(new RegExp("[\\W_]"));
	if (illegal) {
		throw new Error(
			`Illegal character found in alphabet: ${alphabet.charAt(illegal.index)}`
		);
	}
 
	const duplicate = alphabet.match(new RegExp("(.+)(?=.*?\\1)", "g"));
	if (duplicate) {
		throw new Error(`Duplicate character found in alphabet: ${duplicate[0]}`);
	}
};