Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit c8dea4b

Browse files
baruchvlzKent C. Dodds
authored and
Kent C. Dodds
committed
feat: add inches to metric conversion (#226)
Closes #225
1 parent 3282f0d commit c8dea4b

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

src/inches-to-metric.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
export default inchesToMetric
2+
3+
const cmConversion = 2.54
4+
5+
const mapper = {
6+
cm: cmConversion,
7+
m: cmConversion / 100,
8+
mm: cmConversion * 10,
9+
}
10+
11+
function inchesToMetric(value, unit = 'cm') {
12+
if (isNaN(value)) {
13+
throw new TypeError('First argument must be of type "number"')
14+
}
15+
16+
if (value > 12 || value < 0) {
17+
throw new RangeError('Inches have to be between 0 and 12')
18+
}
19+
20+
if (!mapper[unit]) {
21+
throw new Error('Can only convert inches to meters ("m"), centimeters ("cm"), or milimeters ("mm").')
22+
}
23+
24+
return value * mapper[unit]
25+
}

src/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ import timeSince from './timeSince'
8484
import first from './first'
8585
import mode from './mode-array'
8686
import rollDice from './rollDice'
87+
import inchesToMetric from './inches-to-metric'
8788

8889
export {
8990
reverseArrayInPlace,
@@ -172,4 +173,5 @@ export {
172173
first,
173174
mode,
174175
rollDice,
176+
inchesToMetric,
175177
}

test/inches-to-metric.js

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import test from 'ava'
2+
import {inchesToMetric} from './../src'
3+
4+
test('should throw error if a number is not passed', t => {
5+
t.throws(() => inchesToMetric('foo'))
6+
})
7+
8+
test('should throw error if inches is out of range value', t => {
9+
t.throws(() => inchesToMetric(22))
10+
t.throws(() => inchesToMetric(-1))
11+
})
12+
13+
test('should throw error if wrong metric value is passed', t => {
14+
t.throws(() => inchesToMetric(12, 'km'))
15+
})
16+
17+
test('should convert inches to centimeters', t => {
18+
t.deepEqual(inchesToMetric(1), 2.54)
19+
t.deepEqual(inchesToMetric(10), 25.4)
20+
})
21+
22+
test('should convert inches to meters', t => {
23+
t.deepEqual(inchesToMetric(1, 'm'), 0.0254)
24+
t.deepEqual(inchesToMetric(10, 'm'), 0.254)
25+
})
26+
27+
test('should convert inches to milimeters', t => {
28+
t.deepEqual(inchesToMetric(1, 'mm'), 25.4)
29+
t.deepEqual(inchesToMetric(10, 'mm'), 254)
30+
})

0 commit comments

Comments
 (0)