-
-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathmode.js
More file actions
44 lines (35 loc) · 1.04 KB
/
mode.js
File metadata and controls
44 lines (35 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// You are given an implementation of calculateMode
// calculateMode's implementation can be broken down into two stages:
// Stage 1. One part of the code tracks the frequency of each value
// Stage 2. The other part finds the value with the highest frequency
// refactor calculateMode by splitting up the code
// into smaller functions using the stages above
// track frequency of each value
function calculateFreq(list) {
let freqs = new Map();
for (let num of list) {
if (typeof num !== "number") {
continue;
}
freqs.set(num, (freqs.get(num) || 0) + 1);
}
return freqs;
}
// Find the value with the highest frequency
function findMaxFreq(freqs) {
let maxFreq = 0;
let mode;
for (let [num, freq] of freqs) {
if (freq > maxFreq) {
mode = num;
maxFreq = freq;
}
}
return [maxFreq, mode];
}
function calculateMode(list) {
const calculatedFrequency = calculateFreq(list);
const [maxFreq, mode] = findMaxFreq(calculatedFrequency);
return maxFreq === 0 ? NaN : mode;
}
module.exports = calculateMode;