benmvp / ama

Ask me anything!
https://github.com/benmvp/ama/issues?q=is%3Aissue+is%3Aclosed
3 stars 3 forks source link

Please explain the use of c.name in the Eloquent Javascript Chapter 5 #20

Closed hkgmahwa closed 4 years ago

hkgmahwa commented 6 years ago
function countBy(items, groupName) {
  let counts = [];
  for (let item of items) {
    let name = groupName(item);
// please explain what is c.name
    let known = counts.findIndex(c => **c.name** == name);
    if (known == -1) {
      counts.push({name, count: 1});
    } else {
      counts[known].count++;
    }
  }
  return counts;
}

console.log(countBy([1, 2, 3, 4, 5], n => n > 2));
// → [{name: false, count: 2}, {name: true, count: 3}]
benmvp commented 5 years ago

Sorry, I never saw this. 😢

Basically the function is going through the list of items and adding them to the counts array. If the object doesn't yet exist, it's pushed onto the array with a count of 1 (counts.push({name, count: 1}). However in order to determine if counts already has the name, it searches counts. counts contains objects of the form {name: 'blah', count: XXX}. So c.name is just the name of an item that's already been added.