Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80681 views
1
2
module.exports = exports = abbrev.abbrev = abbrev
3
4
abbrev.monkeyPatch = monkeyPatch
5
6
function monkeyPatch () {
7
Object.defineProperty(Array.prototype, 'abbrev', {
8
value: function () { return abbrev(this) },
9
enumerable: false, configurable: true, writable: true
10
})
11
12
Object.defineProperty(Object.prototype, 'abbrev', {
13
value: function () { return abbrev(Object.keys(this)) },
14
enumerable: false, configurable: true, writable: true
15
})
16
}
17
18
function abbrev (list) {
19
if (arguments.length !== 1 || !Array.isArray(list)) {
20
list = Array.prototype.slice.call(arguments, 0)
21
}
22
for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
23
args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
24
}
25
26
// sort them lexicographically, so that they're next to their nearest kin
27
args = args.sort(lexSort)
28
29
// walk through each, seeing how much it has in common with the next and previous
30
var abbrevs = {}
31
, prev = ""
32
for (var i = 0, l = args.length ; i < l ; i ++) {
33
var current = args[i]
34
, next = args[i + 1] || ""
35
, nextMatches = true
36
, prevMatches = true
37
if (current === next) continue
38
for (var j = 0, cl = current.length ; j < cl ; j ++) {
39
var curChar = current.charAt(j)
40
nextMatches = nextMatches && curChar === next.charAt(j)
41
prevMatches = prevMatches && curChar === prev.charAt(j)
42
if (!nextMatches && !prevMatches) {
43
j ++
44
break
45
}
46
}
47
prev = current
48
if (j === cl) {
49
abbrevs[current] = current
50
continue
51
}
52
for (var a = current.substr(0, j) ; j <= cl ; j ++) {
53
abbrevs[a] = current
54
a += current.charAt(j)
55
}
56
}
57
return abbrevs
58
}
59
60
function lexSort (a, b) {
61
return a === b ? 0 : a > b ? 1 : -1
62
}
63
64