@Judge1337

Как без рекурсии посчитать сумму свойств вложенных объектов?

Есть задача:

You have to implement function that will count sum of all object properties that are numbers!
You must count in all properties of all nested objects!!!
All object keys are strings!
There can be more than one level of nesting!!!
You solution must not contain recursion!!!

Я написал код, но он видимо не учитывает, что элемент может быть не числом, помогите это исправить:

function objectPropertiesSum(object) {
    var sum = 0;
    for( var el in object ) {
      if( object.hasOwnProperty( el ) ) {
        sum += parseFloat( object[el] );
      }
    }
    return sum;
  }

Вот какой результат выдаёт тест:

Sum of elements for object: {"0":72,"1":"notAnumber","2":98,"3":68,"4":96,"5":111,"6":{"0":"notAnumber","1":{"0":44,"1":49,"2":106,"3":{"0":{"0":90,"1":{"0":{"0":109,"1":"notAnumber","2":"notAnumber","3":"notAnumber"},"1":55,"2":76,"3":"notAnumber","4":57},"2":{"0":{"0":87,"1":77,"2":81,"3":"notAnumber"},"1":67,"2":"notAnumber","3":"notAnumber","4":74},"3":"notAnumber","4":110,"5":110},"1":61,"2":107,"3":110,"4":{"0":{"0":"notAnumber","1":87,"2":90,"3":79,"4":{"0":"notAnumber","1":39,"2":101,"3":56}},"1":91,"2":51,"3":{"0":105,"1":37,"2":{"0":{"0":83,"1":70,"2":{"0":66,"1":43}},"1":77,"2":65,"3":"notAnumber"},"3":{"0":104,"1":76,"2":79,"3":109},"4":"notAnumber"},"4":70,"5":96},"5":73,"6":{"0":101,"1":74,"2":59,"3":96,"4":{"0":107,"1":"notAnumber","2":93,"3":32,"4":"notAnumber"},"5":93}},"4":"notAnumber","5":{"0":{"0":"notAnumber","1":31,"2":71,"3":98,"4":{"0":86,"1":{"0":"notAnumber","1":78,"2":91,"3":113},"2":"notAnumber","3":"notAnumber","4":97},"5":{"0":{"0":{"0":35,"1":92,"2":"notAnumber"},"1":107,"2":{"0":64,"1":63,"2":{"0":{"0":80},"1":33}},"3":{"0":99,"1":78,"2":"notAnumber"}},"1":"notAnumber","2":41,"3":103,"4":{"0":40,"1":{"0":"notAnumber","1":30,"2":51},"2":"notAnumber","3":"notAnumber"}}},"1":95,"2":"notAnumber","3":82,"4":90,"5":"notAnumber","6":60},"6":102,"7":{"0":"notAnumber","1":74,"2":78,"3":104,"4":"notAnumber","5":38,"6":{"0":"notAnumber","1":"notAnumber","2":100,"3":79,"4":"notAnumber","5":41}}},"2":"notAnumber","3":108,"4":"notAnumber","5":38,"6":"notAnumber","7":{"0":39,"1":38,"2":47,"3":68,"4":53,"5":93,"6":44,"7":{"0":42,"1":{"0":78,"1":79,"2":32,"3":"notAnumber","4":101,"5":{"0":{"0":"notAnumber","1":69,"2":105,"3":45},"1":"notAnumber","2":95,"3":{"0":46,"1":49,"2":39,"3":107},"4":40}},"2":35,"3":103,"4":{"0":{"0":45,"1":{"0":{"0":66,"1":106,"2":{"0":111,"1":89}},"1":33,"2":35,"3":43},"2":"notAnumber","3":{"0":{"0":"notAnumber","1":{"0":"notAnumber","1":"notAnumber"},"2":71},"1":{"0":"notAnumber","1":58,"2":111},"2":98,"3":85},"4":"notAnumber"},"1":{"0":"notAnumber","1":103,"2":"notAnumber","3":68,"4":91},"2":108,"3":"notAnumber","4":99,"5":72},"5":"notAnumber","6":95}},"8":58},"7":105,"8":"notAnumber","9":97} is 10281
Expected: 10281, Actual: NaN
  • Вопрос задан
  • 412 просмотров
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
Будем использовать стек. В начале стек содержит единственное значение - то, которое передано в функцию. Цикл крутится до тех пор, пока стек не окажется пуст. На каждой итерации извлекаем значение из стека, если число - плюсуем к результату, если объект - добавляем значения его свойств в стек.

function sum(data) {
  let result = 0;

  for (const stack = [ data ]; stack.length; ) {
    const n = stack.pop();
    stack.push(...(n instanceof Object ? Object.values(n) : []));
    result += typeof n === 'number' ? n : 0;
  }

  return result;
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы