upload tizen1.0 source
[framework/web/web-ui-fw.git] / build-tools / lib / jslint / nopt / abbrev.js
1
2 module.exports = exports = abbrev.abbrev = abbrev
3
4 abbrev.monkeyPatch = monkeyPatch
5
6 function monkeyPatch () {
7   Array.prototype.abbrev = function () { return abbrev(this) }
8   Object.prototype.abbrev = function () { return abbrev(Object.keys(this)) }
9 }
10
11 function abbrev (list) {
12   if (arguments.length !== 1 || !Array.isArray(list)) {
13     list = Array.prototype.slice.call(arguments, 0)
14   }
15   for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
16     args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
17   }
18
19   // sort them lexicographically, so that they're next to their nearest kin
20   args = args.sort(lexSort)
21
22   // walk through each, seeing how much it has in common with the next and previous
23   var abbrevs = {}
24     , prev = ""
25   for (var i = 0, l = args.length ; i < l ; i ++) {
26     var current = args[i]
27       , next = args[i + 1] || ""
28       , nextMatches = true
29       , prevMatches = true
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
36       else {
37         j ++
38         break
39       }
40     }
41     prev = current
42     if (j === cl) {
43       abbrevs[current] = current
44       continue
45     }
46     for (var a = current.substr(0, j) ; j <= cl ; j ++) {
47       abbrevs[a] = current
48       a += current.charAt(j)
49     }
50   }
51   return abbrevs
52 }
53
54 function lexSort (a, b) {
55   return a === b ? 0 : a > b ? 1 : -1
56 }
57
58
59 // tests
60 if (module === require.main) {
61
62 var assert = require("assert")
63   , sys
64 sys = require("util")
65
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))
76 }
77
78 test([ "ruby", "ruby", "rules", "rules", "rules" ],
79 { rub: 'ruby'
80 , ruby: 'ruby'
81 , rul: 'rules'
82 , rule: 'rules'
83 , rules: 'rules'
84 })
85 test(["fool", "foom", "pool", "pope"],
86 { fool: 'fool'
87 , foom: 'foom'
88 , poo: 'pool'
89 , pool: 'pool'
90 , pop: 'pope'
91 , pope: 'pope'
92 })
93 test(["a", "ab", "abc", "abcd", "abcde", "acde"],
94 { a: 'a'
95 , ab: 'ab'
96 , abc: 'abc'
97 , abcd: 'abcd'
98 , abcde: 'abcde'
99 , ac: 'acde'
100 , acd: 'acde'
101 , acde: 'acde'
102 })
103
104 console.log("pass")
105
106 }