abbrev.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. module.exports = exports = abbrev.abbrev = abbrev
  2. abbrev.monkeyPatch = monkeyPatch
  3. function monkeyPatch () {
  4. Object.defineProperty(Array.prototype, 'abbrev', {
  5. value: function () { return abbrev(this) },
  6. enumerable: false, configurable: true, writable: true
  7. })
  8. Object.defineProperty(Object.prototype, 'abbrev', {
  9. value: function () { return abbrev(Object.keys(this)) },
  10. enumerable: false, configurable: true, writable: true
  11. })
  12. }
  13. function abbrev (list) {
  14. if (arguments.length !== 1 || !Array.isArray(list)) {
  15. list = Array.prototype.slice.call(arguments, 0)
  16. }
  17. for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
  18. args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
  19. }
  20. // sort them lexicographically, so that they're next to their nearest kin
  21. args = args.sort(lexSort)
  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) {
  36. j ++
  37. break
  38. }
  39. }
  40. prev = current
  41. if (j === cl) {
  42. abbrevs[current] = current
  43. continue
  44. }
  45. for (var a = current.substr(0, j) ; j <= cl ; j ++) {
  46. abbrevs[a] = current
  47. a += current.charAt(j)
  48. }
  49. }
  50. return abbrevs
  51. }
  52. function lexSort (a, b) {
  53. return a === b ? 0 : a > b ? 1 : -1
  54. }