-3

I saw this block of code here How to count number of values in array?. As a solution for my other question.

This solves my issue but I do not want to use it without knowing what it means. Can someone give me a detailed explanation of this code?

function count(object, key, subKey) {
  const noObject = o => !o || typeof o !== 'object';

  function subCount(object) {
    if (noObject(object)) return 0;
    if (subKey in object) return 1;

    return Object.values(object).reduce((s, o) => s + subCount(o), 0);
  }

  if (noObject(object)) return 0;
  if (key in object) return subCount(object[key]);

  return Object.values(object).reduce((s, o) => s + count(o, key, subKey), 0);
}

Is this used to count the number of values in a JSON array?

Siva
  • 113
  • 1
  • 16

1 Answers1

1

It looks like a deep object counter - so it'll count how many values in an object are themselves objects. It returns 1 if the key(s) you pass are in the object, 0 if the object is not an object, and any other number (including 0 and 1, confusingly) which will be the number of objects.

The second line is an arrow function, and returns a Boolean if the passed object is either falsy or not an object.

The return statement (the last one) goes through each value in the object, and gets the count of each item. And since both subCount and count are recursive, this may go into multiple recursion levels.

(It's also a fairly unconventional and low-performance way to write this function IMHO.)

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • I just have No to little idea what this piece of code does. Just put it here so that I could get some help Disheartened with the all the downvotes tbh. – Siva Jun 27 '19 at 10:41