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

Commit f009f81

Browse files
ArupSenKent C. Dodds
authored andcommitted
feat(dec2bin): Add a decimal to binary function #67
* feat(dec2bin): Add a decimal to binary function #67 * feat(dec2bin): Add decimal to binary function Closes #69 * Update message for invalid input from String to RangeError * Update dec2bin to throw RangeError
1 parent db12012 commit f009f81

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

src/dec2bin.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
export default dec2bin
2+
3+
/**
4+
* Converts a decimal integer into binary number
5+
* Only works for positive integers
6+
* Untested for values greater than 32-bit
7+
* Floating point numbers truncated to integer
8+
*
9+
* @param {String} dec - string version of integer
10+
* @return {String} - binary version of input as string
11+
*/
12+
function dec2bin(dec) {
13+
if (parseInt(dec, 10) < 0) {
14+
throw new RangeError('Input must be a positive integer')
15+
} else {
16+
return parseInt(dec, 10).toString(2)
17+
}
18+
}

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import divide from './divide'
1919
import multiply from './multiply'
2020
import square from './square'
2121
import sum from './sum'
22+
import dec2bin from './dec2bin'
2223

2324
export {
2425
flatten,
@@ -42,4 +43,5 @@ export {
4243
multiply,
4344
square,
4445
sum,
46+
dec2bin,
4547
}

test/dec2bin.test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import test from 'ava'
2+
import {dec2bin} from '../src'
3+
4+
test('string is not a number', t => {
5+
const original = 'five'
6+
const expected = 'NaN'
7+
const actual = dec2bin(original)
8+
t.deepEqual(actual, expected)
9+
})
10+
11+
test('throws error if number is less than zero', t => {
12+
const original = '-123'
13+
//const actual = dec2bin(original)
14+
const error = t.throws(() => {
15+
dec2bin(original)
16+
},RangeError)
17+
t.is(error.message, 'Input must be a positive integer')
18+
})
19+
20+
test('outputs binary version as string', t => {
21+
const original = '1234'
22+
const expected = '10011010010'
23+
const actual = dec2bin(original)
24+
t.deepEqual(actual, expected)
25+
})
26+

0 commit comments

Comments
 (0)