From 6cece088cacea92886849db4f69fc7b7e94c2573 Mon Sep 17 00:00:00 2001 From: Piotr Idzik Date: Wed, 15 May 2024 20:45:13 +0000 Subject: [PATCH] tests: add `HexToDecimal.test.js` --- Conversions/HexToDecimal.js | 5 ++++- Conversions/test/HexToDecimal.test.js | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 Conversions/test/HexToDecimal.test.js diff --git a/Conversions/HexToDecimal.js b/Conversions/HexToDecimal.js index 31ae13932f..e402421399 100644 --- a/Conversions/HexToDecimal.js +++ b/Conversions/HexToDecimal.js @@ -1,4 +1,7 @@ function hexToInt(hexNum) { + if (!/^[0-9A-F]+$/.test(hexNum)) { + throw new Error('Invalid hex string.') + } const numArr = hexNum.split('') // converts number to array return numArr.map((item, index) => { switch (item) { @@ -29,4 +32,4 @@ function hexToDecimal(hexNum) { }, 0) } -export { hexToInt, hexToDecimal } +export { hexToDecimal } diff --git a/Conversions/test/HexToDecimal.test.js b/Conversions/test/HexToDecimal.test.js new file mode 100644 index 0000000000..816c70511d --- /dev/null +++ b/Conversions/test/HexToDecimal.test.js @@ -0,0 +1,24 @@ +import { hexToDecimal } from '../HexToDecimal' + +describe('Testing HexToDecimal', () => { + it.each([ + ['0', 0], + ['1', 1], + ['A', 10], + ['B', 11], + ['C', 12], + ['D', 13], + ['E', 14], + ['F', 15], + ['10', 16], + ['859', 2137], + ['4D2', 1234], + ['81323ABD92', 554893491602] + ])('check with %s', (hexStr, expected) => { + expect(hexToDecimal(hexStr)).toBe(expected) + }) + + it.each(['a', '-1', 'G', ''])('throws for %s', (hexStr) => { + expect(() => hexToDecimal(hexStr)).toThrowError() + }) +})