-
-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathmode.js
More file actions
41 lines (31 loc) · 951 Bytes
/
mode.js
File metadata and controls
41 lines (31 loc) · 951 Bytes
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
// 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
function calculateFrequency(list) {
// track frequency of each value
let freqs = new Map();
for (let num of list) {
if (typeof num !== "number") {
continue;
}
freqs.set(num, (freqs.get(num) || 0) + 1);
}
return freqs;
}
function calculateMode(list) {
const freqs = calculateFrequency(list);
// Find the value with the highest frequency
let maxFreq = 0;
let mode;
for (let [num, freq] of freqs) {
if (freq > maxFreq) {
mode = num;
maxFreq = freq;
}
}
return maxFreq === 0 ? NaN : mode;
}
module.exports = calculateMode;