Skip to content

Instantly share code, notes, and snippets.

@fundon
Last active August 29, 2015 14:02
Show Gist options
  • Save fundon/fa44fca1da25d6892440 to your computer and use it in GitHub Desktop.
Save fundon/fa44fca1da25d6892440 to your computer and use it in GitHub Desktop.
pathing - 一個簡單、快速 URL path 詞法分析器

https://github.com/fundon/pathing

語法:默認使用{}作爲標籤分隔符。

/posts/{id}       默認使用 [^/]+ 正則表達式.
/posts/{id:\\d+}  使用 `\d+` 正則表達式.

用例:

var pathing = require('pathing');
var tokens = pathing('/{controller}/{action}/{id:\\d+}');
/*
tokens:
  [
    { name: 'SLASH', value: '/', pos: 0 },
    { name: 'PLACEHOLDER', value: 'controller', pos: 1, regexp: '[^/]+' },
    { name: 'SLASH', value: '/', pos: 13 },
    { name: 'PLACEHOLDER', value: 'action', pos: 14, regexp: '[^/]+' }
    { name: 'SLASH', value: '/', pos: 22 },
    { name: 'PLACEHOLDER', value: 'id', pos: 23, regexp: '\\d+' } ]
  ]
*/

var tokens = pathing('{year}-{month}-{day}');
/*
tokens:
  [
    { name: 'PLACEHOLDER', value: 'year', pos: 0, regexp: '[^/]+' },
    { name: 'IDENTIFIER', value: '-', pos: 6 },
    { name: 'PLACEHOLDER', value: 'month', pos: 7, regexp: '[^/]+' },
    { name: 'IDENTIFIER', value: '-', pos: 14 },
    { name: 'PLACEHOLDER', value: 'day', pos: 15, regexp: '[^/]+' }
  ]
*/

自定義分隔符:

var tokens = pathing('/posts/<id>', { open: '<', close: '>' });
/*
tokens:
  [
    { name: 'SLASH', value: '/', pos: 0 },
    { name: 'IDENTIFIER', value: 'posts', pos: 1 },
    { name: 'SLASH', value: '/', pos: 6 },
    { name: 'PLACEHOLDER', value: 'id', pos: 7, regexp: '[^/]+' }
  ]
*/

性能

$ make benchmark
path-to-regexp x 123,819 ops/sec ±1.33% (92 runs sampled)
path-to-regexp#mutil-parameters x 155,711 ops/sec ±1.21% (89 runs sampled)
path-to-regexp#longest x 76,582 ops/sec ±1.78% (88 runs sampled)
path-to-regexp#longest... x 44,179 ops/sec ±2.39% (81 runs sampled)
path-to-regexp#special-characters x 426,990 ops/sec ±1.71% (90 runs sampled)
pathing x 1,338,739 ops/sec ±1.72% (88 runs sampled)
pathing#mutil-parameters x 762,336 ops/sec ±1.25% (90 runs sampled)
pathing#longest x 230,568 ops/sec ±1.54% (90 runs sampled)
pathing#longest... x 116,395 ops/sec ±1.51% (92 runs sampled)
pathing#special-characters x 1,730,056 ops/sec ±1.95% (86 runs sampled)
Fastest is pathing#special-characters.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment