import assert from 'node:assert/strict';
// Turns a price like '3.50' into whole cents.
export function toCents(text) {
if (!/^\d+(\.\d{1,2})?$/.test(text)) throw new RangeError('not a price: ' + text);
return Math.round(Number(text) * 100);
}
// What test() does for you: run fn, and count a throw as a failure.
function check(name, fn) {
try {
fn();
console.log('pass', name);
} catch (error) {
console.log('FAIL', name, '->', error.name + ':', error.message.split('\n')[0]);
}
}
check('3.50 is 350 cents', () => {
assert.equal(toCents('3.50'), 350, "toCents('3.50') should be 350");
});
check('0.29 is 29 cents, not 28', () => {
assert.equal(toCents('0.29'), 29, "toCents('0.29') should be 29");
});
check('every price in a list', () => {
assert.deepEqual(['1', '2.5'].map(toCents), [100, 250], 'each price in cents');
});
check('equal on two objects', () => {
assert.equal({cents: 100}, {cents: 100}, 'two object literals are two objects');
});
check('a word is not a price', () => {
assert.throws(() => toCents('abc'), RangeError, "toCents('abc') should throw a RangeError");
});
check('the error names the input', () => {
assert.throws(() => toCents('3,50'), {name: 'RangeError', message: /3,50/}, 'the message should contain 3,50');
});
check('ok and match', () => {
assert.ok(toCents('0') === 0, "toCents('0') should be 0");
assert.match('not a price: x', /^not a price/, 'the message should start with not a price');
});