Skip to content

Commit

Permalink
Call find only one time
Browse files Browse the repository at this point in the history
  • Loading branch information
delvedor committed Jul 13, 2017
1 parent a963dda commit 7253d83
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 21 deletions.
17 changes: 9 additions & 8 deletions index.js
Expand Up @@ -154,6 +154,7 @@ Router.prototype.lookup = function (req, res) {
Router.prototype.find = function (method, path) {
var currentNode = this.tree
var node = null
var kind = 0
var decoded = null
var pindex = 0
var params = []
Expand Down Expand Up @@ -194,16 +195,18 @@ Router.prototype.find = function (method, path) {

if (len === prefixLen) path = path.slice(len)

node = currentNode.find(path[0])
if (!node) return null
kind = node.kind

// static route
node = currentNode.find(path[0], 0)
if (node) {
if (kind === 0) {
currentNode = node
continue
}

// parametric route
node = currentNode.findByKind(1)
if (node) {
if (kind === 1) {
currentNode = node
i = 0
while (i < pathLen && path.charCodeAt(i) !== 47) i++
Expand All @@ -217,8 +220,7 @@ Router.prototype.find = function (method, path) {
}

// wildcard route
node = currentNode.findByKind(2)
if (node) {
if (kind === 2) {
decoded = fastDecode(path)
if (errored) {
return null
Expand All @@ -230,8 +232,7 @@ Router.prototype.find = function (method, path) {
}

// parametric(regex) route
node = currentNode.findByKind(3)
if (node) {
if (kind === 3) {
currentNode = node
i = 0
while (i < pathLen && path.charCodeAt(i) !== 47) i++
Expand Down
21 changes: 8 additions & 13 deletions node.js
Expand Up @@ -23,16 +23,6 @@ Node.prototype.add = function (node) {
this.numberOfChildren++
}

Node.prototype.find = function (label, kind) {
for (var i = 0; i < this.numberOfChildren; i++) {
var child = this.children[i]
if (child.label === label && child.kind === kind && (child.map || child.children.length)) {
return child
}
}
return null
}

Node.prototype.findByLabel = function (label) {
for (var i = 0; i < this.numberOfChildren; i++) {
var child = this.children[i]
Expand All @@ -43,11 +33,16 @@ Node.prototype.findByLabel = function (label) {
return null
}

Node.prototype.findByKind = function (kind) {
Node.prototype.find = function (label) {
for (var i = 0; i < this.numberOfChildren; i++) {
var child = this.children[i]
if (child.kind === kind && (child.map || child.children.length)) {
return child
if (child.map || child.children.length) {
if (child.label === label && child.kind === 0) {
return child
}
if (child.kind > 0) {
return child
}
}
}
return null
Expand Down

0 comments on commit 7253d83

Please sign in to comment.