UNPKG

@extra-array/has-permutation

Version:

Checks if array has a permutation.

32 lines (31 loc) 830 B
'use strict'; function id(v) { return v; } function cmp(a, b) { return a < b ? -1 : (a > b ? 1 : 0); } function searchSubsequence(x, y, fc = null, fm = null) { var fc = fc || cmp, fm = fm || id; var y1 = [...y].map(fm), Y = y1.length; var a = -1, i = -1, j = 0; for (var u of x) { var u1 = fm(u, ++i, x); if (fc(u1, y1[j]) !== 0) continue; if (a < 0) a = i; if (++j >= Y) return a; } return -1; } function hasSubsequence(x, y, fc = null, fm = null) { return searchSubsequence(x, y, fc, fm) >= 0; } function hasPermutation(x, y, fc = null, fm = null) { var x1 = fm ? x.map(fm) : x.slice(); var y1 = fm ? y.map(fm) : y.slice(); return hasSubsequence(x1.sort(), y1.sort(), fc, fm); } module.exports = hasPermutation;