11cb0ef41Sopenharmony_cimodule.exports = abbrev
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_cifunction abbrev (...args) {
41cb0ef41Sopenharmony_ci  let list = args.length === 1 || Array.isArray(args[0]) ? args[0] : args
51cb0ef41Sopenharmony_ci
61cb0ef41Sopenharmony_ci  for (let i = 0, l = list.length; i < l; i++) {
71cb0ef41Sopenharmony_ci    list[i] = typeof list[i] === 'string' ? list[i] : String(list[i])
81cb0ef41Sopenharmony_ci  }
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_ci  // sort them lexicographically, so that they're next to their nearest kin
111cb0ef41Sopenharmony_ci  list = list.sort(lexSort)
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ci  // walk through each, seeing how much it has in common with the next and previous
141cb0ef41Sopenharmony_ci  const abbrevs = {}
151cb0ef41Sopenharmony_ci  let prev = ''
161cb0ef41Sopenharmony_ci  for (let ii = 0, ll = list.length; ii < ll; ii++) {
171cb0ef41Sopenharmony_ci    const current = list[ii]
181cb0ef41Sopenharmony_ci    const next = list[ii + 1] || ''
191cb0ef41Sopenharmony_ci    let nextMatches = true
201cb0ef41Sopenharmony_ci    let prevMatches = true
211cb0ef41Sopenharmony_ci    if (current === next) {
221cb0ef41Sopenharmony_ci      continue
231cb0ef41Sopenharmony_ci    }
241cb0ef41Sopenharmony_ci    let j = 0
251cb0ef41Sopenharmony_ci    const cl = current.length
261cb0ef41Sopenharmony_ci    for (; j < cl; j++) {
271cb0ef41Sopenharmony_ci      const curChar = current.charAt(j)
281cb0ef41Sopenharmony_ci      nextMatches = nextMatches && curChar === next.charAt(j)
291cb0ef41Sopenharmony_ci      prevMatches = prevMatches && curChar === prev.charAt(j)
301cb0ef41Sopenharmony_ci      if (!nextMatches && !prevMatches) {
311cb0ef41Sopenharmony_ci        j++
321cb0ef41Sopenharmony_ci        break
331cb0ef41Sopenharmony_ci      }
341cb0ef41Sopenharmony_ci    }
351cb0ef41Sopenharmony_ci    prev = current
361cb0ef41Sopenharmony_ci    if (j === cl) {
371cb0ef41Sopenharmony_ci      abbrevs[current] = current
381cb0ef41Sopenharmony_ci      continue
391cb0ef41Sopenharmony_ci    }
401cb0ef41Sopenharmony_ci    for (let a = current.slice(0, j); j <= cl; j++) {
411cb0ef41Sopenharmony_ci      abbrevs[a] = current
421cb0ef41Sopenharmony_ci      a += current.charAt(j)
431cb0ef41Sopenharmony_ci    }
441cb0ef41Sopenharmony_ci  }
451cb0ef41Sopenharmony_ci  return abbrevs
461cb0ef41Sopenharmony_ci}
471cb0ef41Sopenharmony_ci
481cb0ef41Sopenharmony_cifunction lexSort (a, b) {
491cb0ef41Sopenharmony_ci  return a === b ? 0 : a > b ? 1 : -1
501cb0ef41Sopenharmony_ci}
51