Skip to content

Commit

Permalink
Add Chemin.extract
Browse files Browse the repository at this point in the history
  • Loading branch information
etienne-dldc committed Oct 22, 2019
1 parent ed996c9 commit 69447c1
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ Accepts a `Chemin` and a `pathname` and return `false` or `CheminMatchResult`.

Accepts the same arguments as `Chemin.match` but return `false` if the path does not match or if `rest` is not empty, otherwise it returns the `params` object directly.

### Chemin.extract(chemin)

Accepts a `Chemin` and return an array of all the `Chemin` it contains (as well as teh `Chemin` itself).

### CheminUtils.splitPathname(pathname)

> Split a pathname and prevent empty parts
Expand Down
15 changes: 15 additions & 0 deletions src/Chemin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const Chemin = {
is: isPattern,
match: matchPattern,
matchExact: matchExactPattern,
extract: extractPatterns,
};

type Part = CheminParams<any, any> | Chemin<any>;
Expand Down Expand Up @@ -196,3 +197,17 @@ function stringifyPattern(pattern: Chemin<any>): string {
.join('/')
);
}

function extractPatterns(chemin: Chemin): Array<Chemin> {
const result: Array<Chemin> = [chemin];
function traverse(current: Part) {
if (isPattern(current)) {
if (result.indexOf(current) === -1) {
result.push(current);
current.parts.forEach(traverse);
}
}
}
chemin.parts.forEach(traverse);
return result;
}
14 changes: 14 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,17 @@ test('serialize correctly', () => {

expect(Chemin.stringify(postAdmin)).toBe('/admin/:userId/post/:postId(number)/edit');
});

test('extract chemins', () => {
const empty = Chemin.create();
const post = Chemin.create(empty, P.constant('post'));
const postFragment = Chemin.create(post, P.number('postId'));
const postAdmin = Chemin.create('admin', P.string('userId'), postFragment, 'edit');

const result = Chemin.extract(postAdmin);
expect(result.length).toBe(4);
expect(result[0]).toBe(postAdmin);
expect(result[1]).toBe(postFragment);
expect(result[2]).toBe(post);
expect(result[3]).toBe(empty);
});

0 comments on commit 69447c1

Please sign in to comment.