From 3f37616376682edeaeed59dfe66a606a61797de4 Mon Sep 17 00:00:00 2001 From: M-Scott-Lassiter Date: Sat, 14 May 2022 07:04:58 -0700 Subject: [PATCH] fix: improve dictionary type checking Passing a boolean value or NaN as a dictionary did not cause an error, and it should have. This updates behavior and adds applicable tests. Resolves: #39 --- index.js | 11 +++++++++-- index.test.js | 12 ++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index b34c9a5..6b1c1e5 100644 --- a/index.js +++ b/index.js @@ -77,8 +77,15 @@ class AlphanumericEncoder { */ set dictionary(newDictionary) { // Check for empty dictionaries - if (newDictionary === null || newDictionary === undefined || newDictionary.length === 0) { - throw new RangeError('The dictionary cannot be null, undefined, or an empty string.') + if ( + typeof newDictionary !== 'string' || + newDictionary.length === 0 || + // eslint-disable-next-line no-self-compare + newDictionary !== newDictionary // This verifies it wasn't passed NaN + ) { + throw new RangeError( + 'The dictionary cannot be null, undefined, boolean, NaN, or an empty string.' + ) } // Check for invalid characters. Using a regular expression, make sure only letters and numbers are allowed. diff --git a/index.test.js b/index.test.js index 07b43f3..2c5b139 100644 --- a/index.test.js +++ b/index.test.js @@ -118,6 +118,18 @@ describe('Dictionary Validation', () => { }).toThrow(/undefined/) }) + test.each([true, false])('Dictionary cannot be boolean %p', (input) => { + expect(() => { + encoder.dictionary = input + }).toThrow(/boolean/) + }) + + test('Dictionary cannot be NaN', () => { + expect(() => { + encoder.dictionary = NaN + }).toThrow(/NaN/) + }) + describe('Valid Dictionaries (no lower case)', () => { setupNewEncoderForTesting()