From c8ee1a3ea0159c9f258e6575221be704a9d11616 Mon Sep 17 00:00:00 2001 From: yeohsoonkeat <44747833+yeohsoonkeat@users.noreply.github.com> Date: Wed, 13 Feb 2019 21:17:40 +0700 Subject: [PATCH] feat(armstrong): add 'armstrong' option (#244) * feat(armstrong): add 'armstrong' option * Update index.js * Update index.js --- src/armstrong.js | 25 +++++++++++++++++++++++++ src/index.js | 2 ++ test/armstrong.test.js | 16 ++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 src/armstrong.js create mode 100644 test/armstrong.test.js diff --git a/src/armstrong.js b/src/armstrong.js new file mode 100644 index 00000000..937f3f59 --- /dev/null +++ b/src/armstrong.js @@ -0,0 +1,25 @@ +export default armstrong + +/** + * This method will check if a number is an armstrong number. + * @param {Number} num number to check + * @return{Boolean} True or false + */ + +function armstrong(num) { + let eachDigit = 0 + let check = 0 + let digit = 0 + for (let i = num; i > 0; i = Math.floor(i / 10)) { + digit = digit + 1 + } + for (let i = num; i > 0; i = Math.floor(i / 10)) { + eachDigit = i % 10 + check = check + Math.pow(eachDigit, digit) + } + if (check === num) { + return true + } else { + return false + } +} diff --git a/src/index.js b/src/index.js index 47ee130c..7e559845 100644 --- a/src/index.js +++ b/src/index.js @@ -92,6 +92,7 @@ import removeElementByIndex from './removeElementByIndex' import clone from './clone' import arrMultiply from './array-multiplier' import second from './second' +import armstrong from './armstrong' export { reverseArrayInPlace, @@ -188,4 +189,5 @@ export { clone, arrMultiply, second, + armstrong, } diff --git a/test/armstrong.test.js b/test/armstrong.test.js new file mode 100644 index 00000000..fd5f4c7c --- /dev/null +++ b/test/armstrong.test.js @@ -0,0 +1,16 @@ +import test from 'ava' +import {armstrong} from '../src' + +test('This number is not an armstrong number', t => { + const object = 123 + const expected = false + const actual = armstrong(object) + t.deepEqual(actual, expected) +}) + +test('This number is an armstrong number', t => { + const object = 371 + const expected = true + const actual = armstrong(object) + t.deepEqual(actual, expected) +})