From cceecc071d1d13c4a12eda9e745e3da783baa6cb Mon Sep 17 00:00:00 2001 From: tina <lt-bloody@riox.eu> Date: Tue, 31 Jul 2018 15:06:16 +0200 Subject: [PATCH] computes the stats about the period lengths, started tests --- lib/periode-length.js | 35 +++++++++++++++++++++++++++++++++++ test/periode-length.spec.js | 16 ++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 lib/periode-length.js create mode 100644 test/periode-length.spec.js diff --git a/lib/periode-length.js b/lib/periode-length.js new file mode 100644 index 00000000..24456858 --- /dev/null +++ b/lib/periode-length.js @@ -0,0 +1,35 @@ +export default function getPeriodLengthStats(cycleLengthArray) { + if (Array.isArray(cycleLengthArray) && (cycleLengthArray.length > 0) && cycleLengthArray.every(cycleLength => { + return (typeof cycleLength === 'number') && !(isNaN(cycleLength)) + })) { + const PeriodLengthStats = {} + const sortedCycleLegthArray = cycleLengthArray.sort((a, b) => { + return a - b + }) + PeriodLengthStats.minimum = sortedCycleLegthArray[0] + PeriodLengthStats.maximum = sortedCycleLegthArray[cycleLengthArray.length - 1] + PeriodLengthStats.mean = cycleLengthArray.reduce(getSum) / cycleLengthArray.length + // median + if (cycleLengthArray.length % 2 == 1) { + PeriodLengthStats.median = sortedCycleLegthArray[(cycleLengthArray.length + 1) / 2 - 1] + } + else { + const middle = cycleLengthArray.length / 2 + PeriodLengthStats.median = (sortedCycleLegthArray[middle - 1] + sortedCycleLegthArray[middle]) / 2 + } + + PeriodLengthStats.stdDeviation = 0 // default + if (cycleLengthArray.length > 1) { + const sumOfSquares = cycleLengthArray.map(cycleLength => { + return Math.pow(cycleLength - PeriodLengthStats.mean, 2) + }).reduce(getSum) + PeriodLengthStats.stdDeviation = Math.sqrt(sumOfSquares / (cycleLengthArray.length - 1 )) + } + return PeriodLengthStats + } + console.error('getPeriodLengthStats requiers an array of numbers with length > 0.') +} + +function getSum(total, num) { + return total + num +} \ No newline at end of file diff --git a/test/periode-length.spec.js b/test/periode-length.spec.js new file mode 100644 index 00000000..3051244e --- /dev/null +++ b/test/periode-length.spec.js @@ -0,0 +1,16 @@ +import chai from 'chai' +import periodInfo from '../lib/period-length' + +const expect = chai.expect + +describe('it calculates the median correctly', () => { + it('works for an odd-numbered array', () => { + const periodLengths = [1, 2, 5, 99, 100] + const result = periodInfo(periodLengths).median + expect(result).to.eql(5) + }) + + /* it('works for an even-numbered array', () => { + + }) */ +}) \ No newline at end of file -- GitLab