Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat request: Expose walk/iterator interface for JSON Pointer #110

Open
beorn opened this issue Aug 28, 2020 · 1 comment
Open

Feat request: Expose walk/iterator interface for JSON Pointer #110

beorn opened this issue Aug 28, 2020 · 1 comment

Comments

@beorn
Copy link

beorn commented Aug 28, 2020

Hi, currently the pointer package only exposes post-iteration dicts/index - it would be nice if the walk function an iterator/generator interface was exposed, e.g.,

for (const [ptr, val] of pointer.entries(myPointer))
  ...

Maybe entries, flatEntries, primitives, or something like that, to select what to iterate over.

@beorn
Copy link
Author

beorn commented Aug 29, 2020

I cobbled together one:

import { join } from "json8-pointer"

/* JSON Pointer iterator
 *
 * yields [ entryPath, entryObj, entryKey, parentPath, parentObj ]
 * but values are of course ignorable, so this works fine:
 *
 * for (const [key, val] of entries(obj)) console.log(key, val)
 */
export function* entries(tree) {
  const isContainer = (o) => typeof o === "object" && o !== null
  const isEnumerable = (o) => Array.isArray(o) || o instanceof Set
  const isKeyvalue = (o) => typeof o === "object" || o instanceof Map

  yield [[], tree]
  yield* children([], tree)

  function* children(parentPath, parentObj) {
    if (!isContainer(parentObj)) return
    if (isEnumerable(parentObj)) {
      let c = 0
      for (const childObj of parentObj) {
        const childKey = String(c++)
        const childPath = join(parentPath, childKey)
        yield [childPath, childObj, childKey, parentPath, parentObj]
        yield* children(childPath, childObj)
      }
      return
    }
    if (isKeyvalue(parentObj)) {
      for (const [childKey, childObj] of Object.entries(parentObj)) {
        const childPath = join(parentPath, childKey)
        yield [childPath, childObj, childKey, parentPath, parentObj]
        yield* children(childPath, childObj)
      }
      return
    }
    throw new TypeError(parentObj + " is not a structure")
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant