I'm trying to get better at javascript and have built a simple function that returns 1 if the mode is equal to the mean, and 0 if not. You can enter an array of numbers into the function:
// tests
meanMode([1,2,3]); - returns 0
meanMode([4,4,4,6,2]); - returns 1
meanMode([4,4,4,6,6,6,2]); - returns 0
To clarify, the mean is the middle number in the array, and mode most occurring number.
When I was writing this, I wondered whether I create too many variables and overcomplicate things. The problems I thought I might be making are:
- There are too many variables
- It's confusing and over complex
- It can be hard to retrace my logic and know what the code does and why it's there
I have a few questions that I hope better coders than myself can answer, as I'm relatively new to javascript:
- Was using a counts variable necessary?
- Are all variable keywords (const & let) optimal?
- Is it wise to include comments to describe what the code does?
- Was declaring the mode variable before assigning its value the best way? Its value depends on a condition
Before writing this I wrote a brief logic plan as follows:
Mode:
- var uniqueVals with unique vals (set)
- for each unique value (uniqueVals.map), count no of occurrences in arr (filter.length) & store as an array
- if all values are identical, return 0, otherwise get the most frequent & store in variable (there may be cases with no mode)
Mean:
- sum all numbers
- divide by no of numbers
And:
- if unique values length is same as arr length, return 0
- if mean = mode, return 1
When people write programming, is it usually best to have a detailed plan to follow? I wonder whether there are any best practices that I could follow to improve my coding ability.
function meanMode(arr) {
let uniqueVals = Array.from(new Set(arr));
let counts = uniqueVals.map(function (c, i, a) {
return arr.filter(function (c2) {
return c2 == c
}).length
}); // [3,1,1]
if (arr.every(sameValues)) {
return 0;
} else {
var mode;
// if highest number in counts appears just once, then there is a mode
if ((counts.filter(function (x) { return x == (Math.max(...counts)) }).length) == 1) {
mode = uniqueVals[counts.indexOf(Math.max(...counts))]; // scope issue?
} else {
return 0;
}
const mean = (arr.reduce(function (a, c) { return a + c })) / (arr.length);
if (mode == mean) {
return 1;
} else {
return 0;
}
}
function sameValues(c, i, a) {
return c == a[0];
}
}