Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active April 29, 2021 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpivo/46affaf4cf2f7425636485c6bcf530c9 to your computer and use it in GitHub Desktop.
Save rpivo/46affaf4cf2f7425636485c6bcf530c9 to your computer and use it in GitHub Desktop.
Creating a JSON Walker Class

Creating a JSON Walker Class

class JsonWalker {
  constructor(content) {
    this.content = content;
  }

  get firstChild() {
    return new JsonWalker(this.content.children[0]);
  }

  get lastChild() {
    return new JsonWalker(this.content.children[this.content.children.length - 1]);
  }
  
  nthChild(n) {
    return new JsonWalker(this.content.children[n - 1]);
  }

  get value() {
    return this.content;
  }

  walkChildren(...addresses) {
    return addresses.reduce((content, address, i) => {
      if (i === addresses.length - 1) return content.nthChild(address).value;
      return content.nthChild(address);
    }, this);
  }
}

const j = new JsonWalker({
  children: [{
    children: [
      { children: ['foo', 'bar', 'baz'] },
      { children: ['coffee', 'soda', 'juice'] }
    ]
  }]
});

console.log(j.firstChild.lastChild.nthChild(2).value); // soda
console.log(j.walkChildren(1, 1, 3)); // baz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment