Add utility belt example
This commit is contained in:
25
examples/utility-belt/package.json
Normal file
25
examples/utility-belt/package.json
Normal file
@@ -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 <hello@stevekinney.net>",
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
0
examples/utility-belt/src/index.js
Normal file
0
examples/utility-belt/src/index.js
Normal file
14
examples/utility-belt/src/string-to-number.js
Normal file
14
examples/utility-belt/src/string-to-number.js
Normal 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;
|
||||||
|
};
|
||||||
15
examples/utility-belt/src/string-to-number.test.js
Normal file
15
examples/utility-belt/src/string-to-number.test.js
Normal 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`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user