/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

// https://stackoverflow.com/questions/722668/traverse-all-the-nodes-of-a-json-object-tree-with-javascript

// the presumption is that this code will be walking the result of parsing
// a JSON object. it should not need to handle all types of JavaScript values,
// only those that can be represented as JSON. if that changes then this can
// add support for set, map, etc.

function* objectWalk(o) {
  const memory = new Set();

  function* innerWalk(o) {
    // make sure not to loop on self-referential objects
    if (memory.has(o)) {
      return;
    }
    memory.add(o);

    for (const key of Object.keys(o)) {
      yield [o, key];

      // check type first as null is far less common.
      if (typeof o[key] === 'object' && o[key]) {
        yield* innerWalk(o[key]);
      }
    }
  }
  yield* innerWalk(o);
}

function* objectOnlyWalk(o) {
  if (typeof o !== 'object') {
    return;
  }
  const stack = [o];
  const memory = new Set();

  function* innerWalk(o) {
    if (memory.has(o)) {
      return;
    }
    memory.add(o);

    yield stack;

    for (const key of Object.keys(o)) {
      if (typeof o[key] === 'object' && o !== null) {
        stack.push(o[key]);
        yield* innerWalk(o[key]);
        stack.pop();
      }
    }
  }

  yield* innerWalk(o);
}

module.exports = {
  objectWalk,
  objectOnlyWalk
};
