Skip to content

Instantly share code, notes, and snippets.

@jido2015
Created August 24, 2018 10:03
Show Gist options
  • Select an option

  • Save jido2015/1d865eb43bb6277c8fe2bdf9047cdd6e to your computer and use it in GitHub Desktop.

Select an option

Save jido2015/1d865eb43bb6277c8fe2bdf9047cdd6e to your computer and use it in GitHub Desktop.
We have a characterScript function and a way to correctly loop over charac- ters. The next step is to count the characters that belong to each script. The following counting abstraction will be useful there:
function countBy(items, groupName) {
let counts = [];
for (let item of items) {
let name = groupName(item);
let known = counts.findIndex(c => c.name == name);
console.log(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));
@jido2015
Copy link
Author

jido2015 commented Aug 24, 2018

// → [{name: false, count: 2}, {name: true, count: 3}]

The book says

'The countBy functions- It returns an array of objects, each of which names a group and tells you the number of elements that were found in that group.

` if (known == -1) {
      counts.push({name, count: 1});

    //No value  from 1 to 5  is (-1).which I understood 

 }
 else {
      counts[known].count++;

   //Here is the problem. 
  // I don't know how the output is formatted this way
  `// → [{name: false, count: 2}, {name: true, count: 3}]`

    }`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment