diff --git a/Maths/StandardDeviation.js b/Maths/StandardDeviation.js new file mode 100644 index 0000000000..2ad21d33da --- /dev/null +++ b/Maths/StandardDeviation.js @@ -0,0 +1,32 @@ +/* + * Returns the standard deviation given an array of integers + * @param number[] nums array of integers + * @return number standard deviation + * @see https://en.wikipedia.org/wiki/Standard_deviation + */ +function standardDeviation(nums) { + if (nums.length < 2) { + throw new Error('At least two numbers in input array are required!') + } + if (!Array.isArray(nums)) { + throw new TypeError('Array required!') + } + + let sum = 0 + for (let i = 0; i < nums.length; i++) { + if (typeof nums[i] != 'number') { + throw new TypeError('Number type required in array input!') + } + sum += nums[i] + } + let avg = sum / nums.length + let deviationSquareSum = 0 + for (let i = 0; i < nums.length; i++) { + let square = Math.pow(nums[i] - avg, 2) + deviationSquareSum += square + } + + return Math.sqrt(deviationSquareSum / nums.length) +} + +export { standardDeviation } diff --git a/Maths/test/StandardDeviation.test.js b/Maths/test/StandardDeviation.test.js new file mode 100644 index 0000000000..f2b3b318bd --- /dev/null +++ b/Maths/test/StandardDeviation.test.js @@ -0,0 +1,36 @@ +import { standardDeviation } from '../StandardDeviation.js' + +test('Calculate STD of 3,5,6,10,23,12,19', () => { + expect(standardDeviation([3, 5, 6, 10, 23, 12, 19])).toBeCloseTo( + 6.9164105353773 + ) +}) + +test('Calculate STD of -2,-5,1,12,23,-81,-23', () => { + expect(standardDeviation([-2, -5, 1, 12, 23, -81, -23])).toBeCloseTo( + 31.598889156399 + ) +}) + +test('Calculate STD of 0,0,0', () => { + expect(standardDeviation([0, 0, 0])).toBeCloseTo(0) +}) + +test('Calculate STD of -7,7', () => { + expect(standardDeviation([-7, 7])).toBeCloseTo(7) +}) + +test('Throw error - array has less than two items', () => { + expect(() => standardDeviation([])).toThrow() + expect(() => standardDeviation([7])).toThrow() +}) + +test('Throw type error - not an array', () => { + expect(() => standardDeviation(2)).toThrow() + expect(() => standardDeviation('not an array')).toThrow() +}) + +test('Throw type error - not a number inside array', () => { + expect(() => standardDeviation([5, 'not a number', 2])).toThrow() + expect(() => standardDeviation([1, [2], 3])).toThrow() +})