SizeLoading saved progress…

Size

Implement size(collection) — return how many elements a collection holds, no matter which kind of collection it is. An array or string reports its .length; a Map or Set reports its .size; a plain object reports the number of its own enumerable keys. This mirrors Lodash's _.size: one function that measures anything you hand it.

Signature

// collection: an array, string, Map, Set, plain object, null, or undefined.
// returns: number — the count of elements (own keys for a plain object).
//   null and undefined return 0 rather than throwing.
function size(collection): number;

Examples

size([1, 2, 3]); // → 3   (array length)
size('hello'); // → 5   (string length)
size({ a: 1, b: 2 }); // → 2   (own key count)
size(new Map([['a', 1]])); // → 1   (Map .size)
size(new Set([1, 2, 3])); // → 3   (Set .size)
size(null); // → 0   (no throw)

Notes

  • Three places to read a count. Arrays and strings use .length; Map and Set use .size; plain objects use the number of keys. Your job is to dispatch to the right one.
  • Dispatch order matters. Check .length, then .size, then fall back to keys. An array also has indexed keys, and a Map has none — picking the wrong order gives the wrong number.
  • Own keys only. For a plain object, count its own enumerable keys, not properties it inherits from its prototype.
  • null and undefined return 0. Don't throw on missing input — match lodash and answer 0.
  • Empty in, zero out. An empty array, string, object, Map, or Set all return 0.
Loading editor…