UNPKG

675 BPlain TextView Raw
1import id from './_id';
2import cmp from './_cmp';
3import type {compareFn, mapFn} from './_types';
4
5/**
6 * Finds first index of a subsequence.
7 * @param x an array
8 * @param y subsequence?
9 * @param fc compare function (a, b)
10 * @param fm map function (v, i, x)
11 */
12function searchSubsequence<T, U=T>(x: Iterable<T>, y: Iterable<T>, fc: compareFn<T|U>=null, fm: mapFn<T, T|U>=null): number {
13 var fc = fc||cmp, fm = fm||id
14 var y1 = [...y].map(fm), Y = y1.length;
15 var a = -1, i = -1, j = 0;
16 for(var u of x) {
17 var u1 = fm(u, ++i, x);
18 if(fc(u1, y1[j])!==0) continue;
19 if(a<0) a = i;
20 if(++j>=Y) return a;
21 }
22 return -1;
23}
24export default searchSubsequence;