File tree Expand file tree Collapse file tree 1 file changed +7
-8
lines changed
Expand file tree Collapse file tree 1 file changed +7
-8
lines changed Original file line number Diff line number Diff line change @@ -2,17 +2,16 @@ function tally(items) {
22 if ( ! Array . isArray ( items ) ) {
33 throw new Error ( "Input must be an array" ) ;
44 }
5- const counts = { } ; // empty object to store tally of key-value pairs
5+ const counts = Object . create ( null ) ; // empty object to store tally of key-value pairs
6+ // object.create(null) creates a new object with no inherited properties
67 for ( const item of items ) {
7- // iterates through each element in the items array
8- if ( counts [ item ] ) {
9- // checks if the item already exists as a key in counts object
10- counts [ item ] += 1 ; // increments the count for that item by 1
11- } else {
12- counts [ item ] = 1 ; // initializes the count for that item to 1
13- }
8+ // iterate through each item in the input array
9+ const key = String ( item ) ; // convert item to string to use as key
10+ counts [ key ] = ( counts [ key ] || 0 ) + 1 ; // increment count for this key
1411 }
1512 return counts ; // returns the final counts object
1613}
1714
1815module . exports = tally ;
16+
17+ console . log ( tally ( [ "toString" , "toString" ] ) ) ;
You can’t perform that action at this time.
0 commit comments