-
Notifications
You must be signed in to change notification settings - Fork 1
/
retrie.co
executable file
·35 lines (32 loc) · 1.07 KB
/
retrie.co
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@Retrie = class
(strings, asPrefixes) ~>
@tree = {}
@add str, asPrefixes for str of strings or ''
# Adds `string` to the trie and returns self.
# If `asPrefixes`, instead adds every prefix of `string`. i.e.:
#
# Retrie().add('ab', true) == '' + Retrie().add('a').add('ab')
#
add: (string, asPrefixes) ->
ref = @tree
for i til string.length
ref = ref[string.charAt i] ||= if asPrefixes then {''} else {}
# Empty string indicates terminator.
asPrefixes or ref <<< {''}
this
toString: ->
function recur
alt = []; cc = []
for chr in it
unless chr then q = true; continue
(if sub = recur it[chr] then alt else cc)push \
(if ~'.?*+^$|(){[\\'indexOf chr then \\ + chr else chr) + sub
return '' if q and sub!?
cconly = not alt.length
cc.length and alt.push if cc.1 then "[#{ cc.join '' }]" else cc.0
re = if alt.1 then "(?:#{ alt.join \| })" else alt.0
q and re = if cconly then re + \? else "(?:#re)?"
re or ''
recur @tree
import {Retrie}
module?exports = this