UNPKG

find-partial-anagrams

Version:

Takes a set of letters and returns all the words in a given word list that can be made using all or a subset of those letters.

61 lines (60 loc) 1.7 kB
const g = "?"; function m(t) { return typeof t == "string" && /^[A-Za-z\?]{1}$/.test(t); } function p(t, r) { const o = []; let c = []; const s = `Input must be a string or array containing only letters (a-z) and wildcards (${g}).`, n = "No word list was provided to search for matches. Provide an array of strings."; if (typeof t == "string") { if (!t || !/^[A-Za-z\?]+$/.test(t)) throw new Error(s); c = t.toLowerCase().split(""); } else if (Array.isArray(t)) { if (t.length === 0 || t.some((e) => !m(e))) throw new Error(s); c = t; } else throw new Error(s); if (!r || r.length === 0) throw new Error(n); return r = r.filter((e) => e.length <= c.length), r.forEach((e) => { const l = e.split(""), i = c.slice(), a = []; l.forEach((d) => { const f = i.indexOf(d); let h = f > -1 ? f : i.indexOf(g); h > -1 && (i.splice(h, 1), a.push(d)); }), a.join("") === e && o.push(e); }), o; } function u(t) { const r = t.sort(); let o = [r[0]]; const c = (s, n) => { let e = 0; for (; e < s.length && e < n.length && s[e] === n[e]; ) e++; return e; }; for (let s = 1; s < r.length; s++) { const n = c(r[s - 1], r[s]), e = r[s].slice(n); o.push(`${n}${e}`); } return o; } function w(t) { var c, s; const r = t; let o = [r[0]]; for (let n = 1; n < r.length; n++) { const e = (s = (c = r[n].match(/^[0-9]+/)) == null ? void 0 : c[0]) != null ? s : "0", l = o[n - 1].slice(0, parseInt(e)), i = r[n].slice(e.length), a = `${l}${i}`; o.push(a); } return o; } export { u as compressWordList, w as decompressWordList, p as findPartialAnagrams, m as isChar };