From a597ebdad72bb7822a885745cbbe7a22eb0711df Mon Sep 17 00:00:00 2001 From: Andrea D'Agostino Date: Sun, 20 Jan 2019 22:37:33 +0100 Subject: [PATCH] feat(mode): Add array mode function --- src/index.js | 2 ++ src/mode-array.js | 31 +++++++++++++++++++++++++++++++ test/mode.test.js | 23 +++++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 src/mode-array.js create mode 100644 test/mode.test.js diff --git a/src/index.js b/src/index.js index 3eeeb921..287d91c7 100644 --- a/src/index.js +++ b/src/index.js @@ -82,6 +82,7 @@ import BitwiseAnd from './BitwiseAnd' import copyArrayByValue from './copyArrayByValue' import timeSince from './timeSince' import first from './first' +import mode from './mode-array' export { reverseArrayInPlace, @@ -168,4 +169,5 @@ export { copyArrayByValue, timeSince, first, + mode, } diff --git a/src/mode-array.js b/src/mode-array.js new file mode 100644 index 00000000..0260418a --- /dev/null +++ b/src/mode-array.js @@ -0,0 +1,31 @@ +export default mode + +/** + * Original Source: https://stackoverflow.com/a/1053865 + * + * This method will return the element with the highest occurrence in an array. + * + * @param {Array} array - The array + * @return {*} - The element which has the highest occurrence + */ +function mode(array) { + if (array.length === 0) { + return null + } + const modeMap = {} + let maxEl = array[0] + let maxCount = 1 + for (let i = 0; i < array.length; i++) { + const el = array[i] + if (modeMap[el] === undefined) { + modeMap[el] = 1 + } else { + modeMap[el]++ + } + if (modeMap[el] > maxCount) { + maxEl = el + maxCount = modeMap[el] + } + } + return maxEl +} diff --git a/test/mode.test.js b/test/mode.test.js new file mode 100644 index 00000000..df9f9249 --- /dev/null +++ b/test/mode.test.js @@ -0,0 +1,23 @@ +import test from 'ava' +import {mode} from '../src' + +test('mode in an empty array', t => { + const array = [] + const expected = null + const actual = mode(array) + t.deepEqual(actual, expected) +}) + +test('mode in an array of string elements', t => { + const array = ['apple', 'pear', 'banana', 'pear'] + const expected = 'pear' + const actual = mode(array) + t.deepEqual(actual, expected) +}) + +test('mode in an array of int elements', t => { + const array = [1, 2, 3, 4, 3, 5] + const expected = 3 + const actual = mode(array) + t.deepEqual(actual, expected) +})