Read here. Code on desktop. The coding workspace opens on screens 1024px and wider.
JavaScript interview question
Size
easy10 min
Return the number of entries in an array, string, object, Map, or Set using the counting rule for that collection.
Requirements
Implement size(collection). Arrays use length, including sparse slots; strings use JavaScript length in UTF-16 code units.
Maps and Sets use their size property. Plain record objects, including null-prototype records, count only their own enumerable string keys.
Return 0 for null, undefined, numbers, booleans, symbols, bigints, and functions. Do not infer collection size from a function arity or an object length property.
Ignore inherited, non-enumerable, and symbol object keys. Do not mutate inputs or invoke collection values.
Supported collections are from the same JavaScript realm. Unicode code-point/grapheme counting, weak collections, and custom iterable protocols are outside scope.
Examples
Example 1
Input: size([1, 2, 3])
Output: 3
Example 2
Input: size({ a: 1, b: 2 })
Output: 2
Example 3
Input: size(new Set(['a', 'a', 'b']))
Output: 2
Example 4
Input: size(null)
Output: 0
Count entries according to collection type.
What the tests check
Counts array length including sparse slots
Counts string UTF-16 code units
Counts only own enumerable string object keys
Uses Map entries rather than attached properties
Uses distinct Set entries
Returns zero for null and undefined
Returns zero for unsupported scalars and functions
Supports null-prototype records and ignores length semantics
Returns zero for empty supported collections
Leaves frozen input and collection contents unchanged