index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. module.exports = abbrev
  2. function abbrev (...args) {
  3. let list = args.length === 1 || Array.isArray(args[0]) ? args[0] : args
  4. for (let i = 0, l = list.length; i < l; i++) {
  5. list[i] = typeof list[i] === 'string' ? list[i] : String(list[i])
  6. }
  7. // sort them lexicographically, so that they're next to their nearest kin
  8. list = list.sort(lexSort)
  9. // walk through each, seeing how much it has in common with the next and previous
  10. const abbrevs = {}
  11. let prev = ''
  12. for (let ii = 0, ll = list.length; ii < ll; ii++) {
  13. const current = list[ii]
  14. const next = list[ii + 1] || ''
  15. let nextMatches = true
  16. let prevMatches = true
  17. if (current === next) {
  18. continue
  19. }
  20. let j = 0
  21. const cl = current.length
  22. for (; j < cl; j++) {
  23. const curChar = current.charAt(j)
  24. nextMatches = nextMatches && curChar === next.charAt(j)
  25. prevMatches = prevMatches && curChar === prev.charAt(j)
  26. if (!nextMatches && !prevMatches) {
  27. j++
  28. break
  29. }
  30. }
  31. prev = current
  32. if (j === cl) {
  33. abbrevs[current] = current
  34. continue
  35. }
  36. for (let a = current.slice(0, j); j <= cl; j++) {
  37. abbrevs[a] = current
  38. a += current.charAt(j)
  39. }
  40. }
  41. return abbrevs
  42. }
  43. function lexSort (a, b) {
  44. return a === b ? 0 : a > b ? 1 : -1
  45. }