2 module.exports = exports = abbrev.abbrev = abbrev
4 abbrev.monkeyPatch = monkeyPatch
6 function monkeyPatch () {
7 Array.prototype.abbrev = function () { return abbrev(this) }
8 Object.prototype.abbrev = function () { return abbrev(Object.keys(this)) }
11 function abbrev (list) {
12 if (arguments.length !== 1 || !Array.isArray(list)) {
13 list = Array.prototype.slice.call(arguments, 0)
15 for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
16 args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
19 // sort them lexicographically, so that they're next to their nearest kin
20 args = args.sort(lexSort)
22 // walk through each, seeing how much it has in common with the next and previous
25 for (var i = 0, l = args.length ; i < l ; i ++) {
27 , next = args[i + 1] || ""
30 if (current === next) continue
31 for (var j = 0, cl = current.length ; j < cl ; j ++) {
32 var curChar = current.charAt(j)
33 nextMatches = nextMatches && curChar === next.charAt(j)
34 prevMatches = prevMatches && curChar === prev.charAt(j)
35 if (nextMatches || prevMatches) continue
43 abbrevs[current] = current
46 for (var a = current.substr(0, j) ; j <= cl ; j ++) {
48 a += current.charAt(j)
54 function lexSort (a, b) {
55 return a === b ? 0 : a > b ? 1 : -1
60 if (module === require.main) {
62 var assert = require("assert")
66 console.log("running tests")
67 function test (list, expect) {
68 var actual = abbrev(list)
69 assert.deepEqual(actual, expect,
70 "abbrev("+sys.inspect(list)+") === " + sys.inspect(expect) + "\n"+
71 "actual: "+sys.inspect(actual))
72 actual = abbrev.apply(exports, list)
73 assert.deepEqual(abbrev.apply(exports, list), expect,
74 "abbrev("+list.map(JSON.stringify).join(",")+") === " + sys.inspect(expect) + "\n"+
75 "actual: "+sys.inspect(actual))
78 test([ "ruby", "ruby", "rules", "rules", "rules" ],
85 test(["fool", "foom", "pool", "pope"],
93 test(["a", "ab", "abc", "abcd", "abcde", "acde"],