From 62c32443b87bcaae26b517b5f9958643919c0a05 Mon Sep 17 00:00:00 2001 From: Michael Iwersen Date: Sun, 31 Jan 2016 01:11:51 +0100 Subject: [PATCH] FIxed a bug with / and /: or /* generating an empty node --- package.json | 2 +- src/tree.js | 20 ++++++++++++-------- test/tree.js | 21 +++++++++++++++++++++ 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index 1f89fff..4828a8a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "radix-tree", - "version": "0.3.3", + "version": "0.3.4", "description": "Node.js version of a radix tree usable for routers or url path based storage.", "main": "index.js", "engines": { diff --git a/src/tree.js b/src/tree.js index 0580a89..c2ce56f 100644 --- a/src/tree.js +++ b/src/tree.js @@ -112,11 +112,13 @@ export class Tree { throw new Error('Param node can not be appended to an already existing path') } - child.path = path.substr(offset, index - offset) + if (offset < index - offset) { + child.path = path.substr(offset, index - offset) - offset = index - node.append(child) - node = child + offset = index + node.append(child) + node = child + } child = new Node() child.type = Node.PARAM @@ -125,11 +127,13 @@ export class Tree { throw new Error('Param node can not be appended to an already existing path') } - child.path = path.substr(offset, index - offset) + if (offset < index - offset) { + child.path = path.substr(offset, index - offset) - offset = index - node.append(child) - node = child + offset = index + node.append(child) + node = child + } child = new Node() child.type = Node.CATCHALL diff --git a/test/tree.js b/test/tree.js index 32ecbc9..2936397 100644 --- a/test/tree.js +++ b/test/tree.js @@ -136,6 +136,17 @@ describe('Tree', function() { expect(instance.find('/users/testuser/messages/123')).to.deep.equal({path: '/users/:userId/messages/:messageId', params: {userId: 'testuser', messageId: '123'}}) }) + it('should return the catchall param', function () { + let instance = new Tree() + + instance.add('/') + instance.add('/:id') + + expect(instance.find('/')).to.deep.equal({path: '/'}) + expect(instance.find('/some')).to.deep.equal({path: '/:id', params: {id: 'some'}}) + }) + + it('should return the catchall param', function () { let instance = new Tree() @@ -146,6 +157,16 @@ describe('Tree', function() { expect(instance.find('/users/some/path')).to.deep.equal({path: '/users/*api', params: {api: 'some/path'}}) }) + it('should return the catchall param', function () { + let instance = new Tree() + + instance.add('/') + instance.add('/*api') + + expect(instance.find('/')).to.deep.equal({path: '/'}) + expect(instance.find('/some/path')).to.deep.equal({path: '/*api', params: {api: 'some/path'}}) + }) + it('should be possible to mix both types', function () { let instance = new Tree()