Skip to curriculum
Jump to the editor

1.4. Size of any collection

Easy
Topics
10–15 min

A badge shows how many items are in a cart, a list of filters or a set of selected rows, and the data behind it might be an array, a Map, a Set, a plain object of id-to-item pairs, or a string. Each one counts its items in a different way: length, size, or its keys. Write one size function that knows them all.

Write size(value) in size.js.

Signature

JAVASCRIPT
function size(value) // a number of items

Requirements

  1. null and undefined have size 0.
  2. A string's size is its number of code points: an emoji such as "πŸ˜€" counts once, though its length is 2. A letter followed by a combining accent counts as two.
  3. An array's size is its length, holes included. Extra non-index properties on the array do not count.
  4. A Map or a Set (or a subclass of either) has the size its size property reports.
  5. Any other object (plain objects, arguments, typed arrays, class instances) has the number of its own, enumerable, string keys. Inherited, non-enumerable and symbol keys do not count.
  6. Numbers, booleans, symbols, bigints and functions have size 0.
  7. A WeakMap or a WeakSet cannot be counted: size throws a TypeError.

Examples

JAVASCRIPT
size("pebbles");                 // 7
size("πŸ˜€");                      // 1
size([1, , 3]);                  // 3
size(new Map([["a", 1]]));       // 1
JAVASCRIPT
size({ a: 1, b: undefined });    // 2
size(Object.create({ a: 1 }));   // 0: a is inherited
size(null);                      // 0
size(function (a, b) {});        // 0
JAVASCRIPT
size(new WeakSet());             // throws TypeError

Environment

  • Plain JavaScript in a browser page; the tests call the global size from size.js.
  • Grapheme clusters (what a reader sees as one letter) are not part of this problem.
  • Any built-in may be used.

Hints

  1. What does for (const ch of "πŸ˜€") loop over, and how many times?
  2. Which collections keep their items somewhere Object.keys cannot see?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…