@extra-array/search-subsequence
Version:
Finds first index of a subsequence.
24 lines (23 loc) • 533 B
JavaScript
;
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;
}
module.exports = searchSubsequence;