From c8dea4b62f1a082d3b943fdf3a31ecb72f85d88c Mon Sep 17 00:00:00 2001 From: Baruch Date: Fri, 25 Jan 2019 15:25:26 +0100 Subject: [PATCH] feat: add inches to metric conversion (#226) Closes #225 --- src/inches-to-metric.js | 25 +++++++++++++++++++++++++ src/index.js | 2 ++ test/inches-to-metric.js | 30 ++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 src/inches-to-metric.js create mode 100644 test/inches-to-metric.js diff --git a/src/inches-to-metric.js b/src/inches-to-metric.js new file mode 100644 index 00000000..be704e0b --- /dev/null +++ b/src/inches-to-metric.js @@ -0,0 +1,25 @@ +export default inchesToMetric + +const cmConversion = 2.54 + +const mapper = { + cm: cmConversion, + m: cmConversion / 100, + mm: cmConversion * 10, +} + +function inchesToMetric(value, unit = 'cm') { + if (isNaN(value)) { + throw new TypeError('First argument must be of type "number"') + } + + if (value > 12 || value < 0) { + throw new RangeError('Inches have to be between 0 and 12') + } + + if (!mapper[unit]) { + throw new Error('Can only convert inches to meters ("m"), centimeters ("cm"), or milimeters ("mm").') + } + + return value * mapper[unit] +} diff --git a/src/index.js b/src/index.js index 67cfeee6..e8b98a08 100644 --- a/src/index.js +++ b/src/index.js @@ -84,6 +84,7 @@ import timeSince from './timeSince' import first from './first' import mode from './mode-array' import rollDice from './rollDice' +import inchesToMetric from './inches-to-metric' export { reverseArrayInPlace, @@ -172,4 +173,5 @@ export { first, mode, rollDice, + inchesToMetric, } diff --git a/test/inches-to-metric.js b/test/inches-to-metric.js new file mode 100644 index 00000000..407cc05b --- /dev/null +++ b/test/inches-to-metric.js @@ -0,0 +1,30 @@ +import test from 'ava' +import {inchesToMetric} from './../src' + +test('should throw error if a number is not passed', t => { + t.throws(() => inchesToMetric('foo')) +}) + +test('should throw error if inches is out of range value', t => { + t.throws(() => inchesToMetric(22)) + t.throws(() => inchesToMetric(-1)) +}) + +test('should throw error if wrong metric value is passed', t => { + t.throws(() => inchesToMetric(12, 'km')) +}) + +test('should convert inches to centimeters', t => { + t.deepEqual(inchesToMetric(1), 2.54) + t.deepEqual(inchesToMetric(10), 25.4) +}) + +test('should convert inches to meters', t => { + t.deepEqual(inchesToMetric(1, 'm'), 0.0254) + t.deepEqual(inchesToMetric(10, 'm'), 0.254) +}) + +test('should convert inches to milimeters', t => { + t.deepEqual(inchesToMetric(1, 'mm'), 25.4) + t.deepEqual(inchesToMetric(10, 'mm'), 254) +})