Add utility belt example

This commit is contained in:
Steve Kinney
2024-09-29 16:55:08 -06:00
parent 240bfb6dde
commit f8ad1b2586
4 changed files with 54 additions and 0 deletions

View File

View File

@@ -0,0 +1,14 @@
/**
* Converts a string to a number or throws an error if the string is not a number.
* @param {string} value
* @returns {number} The number.
*/
export const stringToNumber = (value) => {
const number = Number(value);
if (isNaN(number)) {
throw new Error(`'${value}' cannot be parsed as a number.`);
}
return number;
};

View File

@@ -0,0 +1,15 @@
import { describe, it, expect } from 'vitest';
import { stringToNumber } from './string-to-number';
describe('stringToNumber', () => {
it('converts a string to a number', () => {
expect(stringToNumber('42')).toBe(42);
});
it('throws an error if given a string that is not a number', () => {
const value = 'foo';
expect(() => stringToNumber(value)).toThrowError(
`cannot be parsed as a number`,
);
});
});