From f8ad1b25866c6e9c5a15356116f966f71477cc28 Mon Sep 17 00:00:00 2001 From: Steve Kinney Date: Sun, 29 Sep 2024 16:55:08 -0600 Subject: [PATCH] Add utility belt example --- examples/utility-belt/package.json | 25 +++++++++++++++++++ examples/utility-belt/src/index.js | 0 examples/utility-belt/src/string-to-number.js | 14 +++++++++++ .../utility-belt/src/string-to-number.test.js | 15 +++++++++++ 4 files changed, 54 insertions(+) create mode 100644 examples/utility-belt/package.json create mode 100644 examples/utility-belt/src/index.js create mode 100644 examples/utility-belt/src/string-to-number.js create mode 100644 examples/utility-belt/src/string-to-number.test.js diff --git a/examples/utility-belt/package.json b/examples/utility-belt/package.json new file mode 100644 index 0000000..e06f64a --- /dev/null +++ b/examples/utility-belt/package.json @@ -0,0 +1,25 @@ +{ + "name": "utility-belt", + "version": "1.0.0", + "main": "src/index.js", + "type": "module", + "scripts": { + "start": "vitest --ui", + "test": "vitest" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/stevekinney/testing-javascript.git" + }, + "author": "Steve Kinney ", + "license": "MIT", + "bugs": { + "url": "https://github.com/stevekinney/testing-javascript/issues" + }, + "homepage": "https://github.com/stevekinney/testing-javascript#readme", + "devDependencies": { + "@vitest/ui": "^2.1.1", + "vite": "^5.4.5", + "vitest": "^2.1.1" + } +} diff --git a/examples/utility-belt/src/index.js b/examples/utility-belt/src/index.js new file mode 100644 index 0000000..e69de29 diff --git a/examples/utility-belt/src/string-to-number.js b/examples/utility-belt/src/string-to-number.js new file mode 100644 index 0000000..611af64 --- /dev/null +++ b/examples/utility-belt/src/string-to-number.js @@ -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; +}; diff --git a/examples/utility-belt/src/string-to-number.test.js b/examples/utility-belt/src/string-to-number.test.js new file mode 100644 index 0000000..95c252d --- /dev/null +++ b/examples/utility-belt/src/string-to-number.test.js @@ -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`, + ); + }); +});