falcor-router icon indicating copy to clipboard operation
falcor-router copied to clipboard

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

Open greim opened this issue 9 years ago • 3 comments
trafficstars

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';
}

greim avatar Dec 03 '15 20:12 greim

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.

ThePrimeagen avatar Dec 04 '15 03:12 ThePrimeagen

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?

greim avatar Dec 04 '15 18:12 greim

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.

ThePrimeagen avatar Dec 04 '15 19:12 ThePrimeagen