Skip to content

Commit

Permalink
perf(router): sort handlers by score only when necessary (#3697)
Browse files Browse the repository at this point in the history
* perf(router): sort handlers by score only when necessary

* add tests

* Update node.test.ts
  • Loading branch information
EdamAme-x authored Nov 23, 2024
1 parent 8717946 commit 3059741
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
11 changes: 11 additions & 0 deletions src/router/trie-router/node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,17 @@ describe('Name path', () => {
expect(resB[0][0]).toEqual('resource')
expect(resB[0][1]).toEqual({ id: 'b' })
})

it('Should return a sorted values', () => {
const node = new Node()
node.insert('get', '/resource/a', 'A')
node.insert('get', '/resource/*', 'Star')
const [res] = node.search('get', '/resource/a')
expect(res).not.toBeNull()
expect(res.length).toBe(2)
expect(res[0][0]).toEqual('A')
expect(res[1][0]).toEqual('Star')
})
})

describe('Name path - Multiple route', () => {
Expand Down
11 changes: 7 additions & 4 deletions src/router/trie-router/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,10 +198,13 @@ export class Node<T> {

curNodes = tempNodes
}
const results = handlerSets.sort((a, b) => {
return a.score - b.score
})

return [results.map(({ handler, params }) => [handler, params] as [T, Params])]
if (handlerSets.length > 1) {
handlerSets.sort((a, b) => {
return a.score - b.score
})
}

return [handlerSets.map(({ handler, params }) => [handler, params] as [T, Params])]
}
}

0 comments on commit 3059741

Please sign in to comment.