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

Feature request: Easy way to iterate every path in a pathSet #152

Open
greim opened this issue Dec 3, 2015 · 3 comments
Open

Feature request: Easy way to iterate every path in a pathSet #152

greim opened this issue Dec 3, 2015 · 3 comments

Comments

@greim
Copy link

greim commented Dec 3, 2015

Maybe this is just due to my own peculiar habits for implementing route handlers, or maybe this would be useful to everyone. I'll let you be the judge of that!

Anyhow, it would be nice to have built-in way to iterate every path in the pathSet passed to a route handler. For example something like this:

{
  route: 'users[{keys:ids}][{keys:props}]',
  async get(pathSet) {
    // pathSet is [ 'users', [ '123', '456' ], [ 'username', 'email' ] ]
    for (const path of pathSet.all()) { console.log(path); }
    // [ 'users', '123', 'username' ]
    // [ 'users', '123', 'email' ]
    // [ 'users', '456', 'username' ]
    // [ 'users', '456', 'email' ]
  }
}

Here's my implementation for example, which I've been using in all my route handlers.

export function* all(pathSet, pointer = 0, path = []) {
  if (pointer >= pathSet.length) {
    yield path.slice();
  } else {
    const thing = pathSet[pointer];
    for (const x of iterateThing(thing)) {
      path.push(x);
      yield* all(pathSet, pointer + 1, path);
      path.pop();
    }
  }
}

function* iterateThing(thing) {
  if (Array.isArray(thing)) {
    for (const subthing of thing) {
      yield* iterateThing(subthing);
    }
  } else if (isRange(thing)) {
    const { from, to } = thing;
    for (let i=from; i<=to; i++) {
      yield i;
    }
  } else {
    yield thing;
  }
}

function isRange(thing) {
  return thing && typeof thing.from === 'number';
}
@ThePrimeagen
Copy link
Contributor

Yes, that is essentially how the walkPath works as well. This could be useful. It would more than likely be put into the falcor-path-utils repo. Its useful.

@greim
Copy link
Author

greim commented Dec 4, 2015

Thanks for the response. I haven't looked much into falcor-path-utils, I'll have to check it out. Will it be attached as a method ala pathSet.all(), or is the idea for people to import falcor-path-utils and use it in their route handlers?

@ThePrimeagen
Copy link
Contributor

In the end pathSets are just Arrays of Arrays. So adding a method would be a bit yucky. But a utility method is where its at.

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

2 participants