Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
1.4. Size of any collection
Easy
Topics
This question is in
1. Types, equality and numbersA 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
function size(value) // a number of itemsRequirements
nullandundefinedhave size 0.- A string's size is its number of code points: an emoji such as "π" counts once, though its
lengthis 2. A letter followed by a combining accent counts as two. - An array's size is its
length, holes included. Extra non-index properties on the array do not count. - A
Mapor aSet(or a subclass of either) has the size itssizeproperty reports. - 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. - Numbers, booleans, symbols, bigints and functions have size 0.
- A
WeakMapor aWeakSetcannot be counted:sizethrows aTypeError.
Examples
size("pebbles"); // 7
size("π"); // 1
size([1, , 3]); // 3
size(new Map([["a", 1]])); // 1size({ a: 1, b: undefined }); // 2
size(Object.create({ a: 1 })); // 0: a is inherited
size(null); // 0
size(function (a, b) {}); // 0size(new WeakSet()); // throws TypeErrorEnvironment
- Plain JavaScript in a browser page; the tests call the global
sizefromsize.js. - Grapheme clusters (what a reader sees as one letter) are not part of this problem.
- Any built-in may be used.
Hints
- What does
for (const ch of "π")loop over, and how many times? - Which collections keep their items somewhere
Object.keyscannot 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β¦