JavaScript functions have a special property arguments, which contains all parameters passed to a function, regardless of whether you’ve specified them in the function declaration, or left the parenthesis empty.
We can iterate this variable like an array to get access to every parameter in the order in which they were passed and inspect them.
We can use an object as an associative array to store the number of each type occurrence. Each type will be a property and its value will be the number of times it occurs in the arguments. We can access them just like we would the keys of an array.
Since object properties cannot be sorted, and even if they could, different JavaScript implementations iterate the order differently, we need to transfer the information to an array of key-value pairs. We could use a Map instead of an object, but this cannot be sorted either, so we’ll end up with an array in the end anyway.
Note we are pushing an array with two values to the array which needs to be sorted. Later when we implement a sorting function, we’ll use the second value of the key-value pair – the number of occurrences. All we need to do after the array is sorted is to output the information in the correct format.
The solution:
function result() {
let summary = [];
for (let i = 0; i < arguments.length; i++) {
let argumentValue = arguments[i];
let argumentType = typeof(argumentValue);
console.log(`${argumentType}: ${argumentValue}`);
if (!summary[argumentType]) {
summary[argumentType] = 1;
} else {
summary[argumentType]++;
}
}
//prep for sorting
let typesToSort = [];
for (let currentType in summary) {
typesToSort.push([currentType, summary[currentType]]);
}
//sort summary
let sortedTypes = [];
sortedTypes = typesToSort.sort((a, b)=>b[1] - a[1]);
//print summary
for (let item of sortedTypes) {
console.log(`${item[0]} = ${item[1]}`)
}
}
result('cat', 42, 430, 'cat', function () {
console.log('Hello world!');
});