← Daily Logs
GreatFrontEnd

Implement size

EasyJul 2, 2026lodashtype-checkscollections

Lodash's `_.size` looks like a one-liner but it's really four different questions in a trenchcoat: arrays and strings already know their own length, `Map`/`Set` track theirs under a different name, and plain objects don't track a count at all — you have to ask for their keys and count those.

The problem

Implement `size(collection)` returning the number of items it holds: `.length` for arrays and strings, the number of own enumerable properties for plain objects, and `.size` for `Map` and `Set`. Anything else — `null`, `undefined`, a number, a boolean — returns `0`.

The four cases don't share one property name, so there's no single expression that handles all of them — the function has to identify which kind of collection it got before it knows where to look for the count.

The approach

Guard `null`/`undefined` first with `collection == null`, using the loose equality on purpose since it catches both in one check and matches the spec's 'return 0' requirement immediately.

Check arrays and strings next — `Array.isArray(collection) || typeof collection === 'string'` — and return `.length` for either, since both already expose the count directly.

`Map` and `Set` are checked with `instanceof` and return `.size` — the one property name that differs from everything else, which is exactly why it needs its own branch instead of falling through to a generic case.

Anything left that's a plain object falls through to `Object.keys(collection).length`, counting own enumerable keys. Anything that isn't an object at all by this point (a number, boolean, function, symbol) has no notion of size, so the final `return 0` catches it.

The solution

js
/**
 * Gets the size of `collection` by returning its length for array-like values or the number of own enumerable string keyed properties for objects.
 *
 * @param {Array | Object | Map | Set | string | null | undefined} collection The collection to inspect.
 * @returns {number} Returns the collection size.
 */
export default function size(collection) {
  if (collection == null) return 0;
  if (Array.isArray(collection) || typeof collection === "string") return collection.length;
  if (collection instanceof Map || collection instanceof Set) return collection.size;
  if (typeof collection === "object") return Object.keys(collection).length;
  return 0;
}

Time O(n)Space O(1)

All entries