trie.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. /**
  2. * Hostbane-Optimized Trie based on Mnemonist Trie
  3. */
  4. import { fastStringCompare } from 'foxts/fast-string-compare';
  5. import util from 'node:util';
  6. import { noop } from 'foxts/noop';
  7. import { fastStringArrayJoin } from 'foxts/fast-string-array-join';
  8. import { deleteBit, getBit, missingBit, setBit } from 'foxts/bitwise';
  9. import { domainToASCII } from 'node:url';
  10. const START = 1 << 1;
  11. const INCLUDE_ALL_SUBDOMAIN = 1 << 2;
  12. type TrieNode<Meta = any> = [
  13. /** end, includeAllSubdomain (.example.org, ||example.com) */ flag: number,
  14. /** parent */ TrieNode | null,
  15. /** children */ Map<string, TrieNode>,
  16. /** token */ token: string,
  17. /** meta */ Meta
  18. ];
  19. function deepTrieNodeToJSON<Meta = unknown>(node: TrieNode,
  20. unpackMeta: ((meta?: Meta) => string) | undefined) {
  21. const obj: Record<string, unknown> = {
  22. ['[start]']: getBit(node[0], START),
  23. ['[subdomain]']: getBit(node[0], INCLUDE_ALL_SUBDOMAIN)
  24. };
  25. if (node[4] != null) {
  26. if (unpackMeta) {
  27. obj['[meta]'] = unpackMeta(node[4]);
  28. } else {
  29. obj['[meta]'] = node[4];
  30. }
  31. }
  32. node[2].forEach((value, key) => {
  33. obj[key] = deepTrieNodeToJSON(value, unpackMeta);
  34. });
  35. return obj;
  36. }
  37. const createNode = <Meta = unknown>(token: string, parent: TrieNode | null = null): TrieNode => [1, parent, new Map<string, TrieNode>(), token, null] as TrieNode<Meta>;
  38. function hostnameToTokens(hostname: string, hostnameFromIndex: number): string[] {
  39. const tokens = hostname.split('.');
  40. const results: string[] = [];
  41. let token = '';
  42. for (let i = hostnameFromIndex, l = tokens.length; i < l; i++) {
  43. token = tokens[i];
  44. if (token.length > 0) {
  45. results.push(token);
  46. } else {
  47. throw new TypeError(JSON.stringify({ hostname, hostnameFromIndex }, null, 2));
  48. }
  49. }
  50. return results;
  51. }
  52. function walkHostnameTokens(hostname: string, onToken: (token: string) => boolean | null, hostnameFromIndex: number): boolean | null {
  53. const tokens = hostname.split('.');
  54. const l = tokens.length - 1;
  55. // we are at the first of hostname, no splitor there
  56. let token = '';
  57. for (let i = l; i >= hostnameFromIndex; i--) {
  58. token = tokens[i];
  59. if (token.length > 0) {
  60. const t = onToken(token);
  61. if (t === null) {
  62. return null;
  63. }
  64. // if the callback returns true, we should skip the rest
  65. if (t) {
  66. return true;
  67. }
  68. }
  69. }
  70. return false;
  71. }
  72. interface FindSingleChildLeafResult<Meta> {
  73. node: TrieNode<Meta>,
  74. toPrune: TrieNode<Meta> | null,
  75. tokenToPrune: string | null,
  76. parent: TrieNode<Meta>
  77. }
  78. abstract class Triebase<Meta = unknown> {
  79. protected readonly $root: TrieNode<Meta> = createNode('$root');
  80. protected $size = 0;
  81. get root() {
  82. return this.$root;
  83. }
  84. constructor(from?: string[] | Set<string> | null) {
  85. // Actually build trie
  86. if (Array.isArray(from)) {
  87. for (let i = 0, l = from.length; i < l; i++) {
  88. this.add(from[i]);
  89. }
  90. } else if (from) {
  91. from.forEach((value) => this.add(value));
  92. }
  93. }
  94. public abstract add(suffix: string, includeAllSubdomain?: boolean, meta?: Meta, hostnameFromIndex?: number): void;
  95. protected walkIntoLeafWithTokens(
  96. tokens: string[],
  97. onLoop: (node: TrieNode, parent: TrieNode, token: string) => void = noop
  98. ) {
  99. let node: TrieNode = this.$root;
  100. let parent: TrieNode = node;
  101. let token: string;
  102. let child: Map<string, TrieNode<Meta>> = node[2];
  103. // reverse lookup from end to start
  104. for (let i = tokens.length - 1; i >= 0; i--) {
  105. token = tokens[i];
  106. // if (token === '') {
  107. // break;
  108. // }
  109. parent = node;
  110. child = node[2];
  111. // cache node index access is 20% faster than direct access when doing twice
  112. if (child.has(token)) {
  113. node = child.get(token)!;
  114. } else {
  115. return null;
  116. }
  117. onLoop(node, parent, token);
  118. }
  119. return { node, parent };
  120. };
  121. protected walkIntoLeafWithSuffix(
  122. suffix: string,
  123. hostnameFromIndex: number,
  124. onLoop: (node: TrieNode, parent: TrieNode, token: string) => void = noop
  125. ) {
  126. let node: TrieNode = this.$root;
  127. let parent: TrieNode = node;
  128. let child: Map<string, TrieNode<Meta>> = node[2];
  129. const onToken = (token: string) => {
  130. // if (token === '') {
  131. // return true;
  132. // }
  133. parent = node;
  134. child = node[2];
  135. if (child.has(token)) {
  136. node = child.get(token)!;
  137. } else {
  138. return null;
  139. }
  140. onLoop(node, parent, token);
  141. return false;
  142. };
  143. if (walkHostnameTokens(suffix, onToken, hostnameFromIndex) === null) {
  144. return null;
  145. }
  146. return { node, parent };
  147. };
  148. public contains(suffix: string, includeAllSubdomain = suffix[0] === '.'): boolean {
  149. const hostnameFromIndex = suffix[0] === '.' ? 1 : 0;
  150. let node: TrieNode = this.$root;
  151. // let parent: TrieNode = node;
  152. let child: Map<string, TrieNode<Meta>> = node[2];
  153. let result = false;
  154. const onToken = (token: string) => {
  155. // if (token === '') {
  156. // return true;
  157. // }
  158. // parent = node;
  159. child = node[2];
  160. if (child.has(token)) {
  161. node = child.get(token)!;
  162. } else {
  163. if (getBit(node[0], INCLUDE_ALL_SUBDOMAIN)) {
  164. result = true;
  165. }
  166. return null;
  167. }
  168. return false;
  169. };
  170. if (walkHostnameTokens(suffix, onToken, hostnameFromIndex) === null) {
  171. return result;
  172. }
  173. if (includeAllSubdomain) return getBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  174. return getBit(node[0], START);
  175. // if (res === null) return false;
  176. // if (includeAllSubdomain) return getBit(res.node[0], INCLUDE_ALL_SUBDOMAIN);
  177. // return true;
  178. };
  179. private static bfsResults: [node: TrieNode | null, suffix: string[]] = [null, []];
  180. private static dfs<Meta>(this: void, nodeStack: Array<TrieNode<Meta>>, suffixStack: string[][]) {
  181. const node = nodeStack.pop()!;
  182. const suffix = suffixStack.pop()!;
  183. node[2].forEach((childNode, k) => {
  184. // Pushing the child node to the stack for next iteration of DFS
  185. nodeStack.push(childNode);
  186. suffixStack.push([k, ...suffix]);
  187. });
  188. Triebase.bfsResults[0] = node;
  189. Triebase.bfsResults[1] = suffix;
  190. return Triebase.bfsResults;
  191. }
  192. private static dfsWithSort<Meta>(this: void, nodeStack: Array<TrieNode<Meta>>, suffixStack: string[][]) {
  193. const node = nodeStack.pop()!;
  194. const suffix = suffixStack.pop()!;
  195. const child = node[2];
  196. if (child.size) {
  197. const keys = Array.from(child.keys()).sort(Triebase.compare);
  198. for (let i = 0, l = keys.length; i < l; i++) {
  199. const key = keys[i];
  200. const childNode = child.get(key)!;
  201. // Pushing the child node to the stack for next iteration of DFS
  202. nodeStack.push(childNode);
  203. suffixStack.push([key, ...suffix]);
  204. }
  205. }
  206. Triebase.bfsResults[0] = node;
  207. Triebase.bfsResults[1] = suffix;
  208. return Triebase.bfsResults;
  209. }
  210. private walk(
  211. onMatches: (suffix: string[], subdomain: boolean, meta: Meta) => void,
  212. withSort = false,
  213. initialNode = this.$root,
  214. initialSuffix: string[] = []
  215. ) {
  216. const dfsImpl = withSort ? Triebase.dfsWithSort : Triebase.dfs;
  217. const nodeStack: Array<TrieNode<Meta>> = [initialNode];
  218. // Resolving initial string (begin the start of the stack)
  219. const suffixStack: string[][] = [initialSuffix];
  220. let node: TrieNode<Meta> = initialNode;
  221. let r;
  222. do {
  223. r = dfsImpl(nodeStack, suffixStack);
  224. node = r[0]!;
  225. const suffix = r[1];
  226. // If the node is a sentinel, we push the suffix to the results
  227. if (getBit(node[0], START)) {
  228. onMatches(suffix, getBit(node[0], INCLUDE_ALL_SUBDOMAIN), node[4]);
  229. }
  230. } while (nodeStack.length);
  231. };
  232. static compare(this: void, a: string, b: string) {
  233. if (a === b) return 0;
  234. return (a.length - b.length) || fastStringCompare(a, b);
  235. }
  236. protected getSingleChildLeaf(tokens: string[]): FindSingleChildLeafResult<Meta> | null {
  237. let toPrune: TrieNode | null = null;
  238. let tokenToPrune: string | null = null;
  239. const onLoop = (node: TrieNode, parent: TrieNode, token: string) => {
  240. // Keeping track of a potential branch to prune
  241. const child = node[2];
  242. const childSize = child.size + (getBit(node[0], INCLUDE_ALL_SUBDOMAIN) ? 1 : 0);
  243. if (toPrune !== null) { // the most near branch that could potentially being pruned
  244. if (childSize >= 1) {
  245. // The branch has some children, the branch need retain.
  246. // And we need to abort prune that parent branch, so we set it to null
  247. toPrune = null;
  248. tokenToPrune = null;
  249. }
  250. } else if (childSize < 1) {
  251. // There is only one token child, or no child at all, we can prune it safely
  252. // It is now the top-est branch that could potentially being pruned
  253. toPrune = parent;
  254. tokenToPrune = token;
  255. }
  256. };
  257. const res = this.walkIntoLeafWithTokens(tokens, onLoop);
  258. if (res === null) return null;
  259. return { node: res.node, toPrune, tokenToPrune, parent: res.parent };
  260. };
  261. /**
  262. * Method used to retrieve every item in the trie with the given prefix.
  263. */
  264. public find(
  265. inputSuffix: string,
  266. subdomainOnly = inputSuffix[0] === '.',
  267. hostnameFromIndex = inputSuffix[0] === '.' ? 1 : 0
  268. // /** @default true */ includeEqualWithSuffix = true
  269. ): string[] {
  270. const inputTokens = hostnameToTokens(inputSuffix, hostnameFromIndex);
  271. const res = this.walkIntoLeafWithTokens(inputTokens);
  272. if (res === null) return [];
  273. const results: string[] = [];
  274. const onMatches = subdomainOnly
  275. ? (suffix: string[], subdomain: boolean) => { // fast path (default option)
  276. const d = domainToASCII(fastStringArrayJoin(suffix, '.'));
  277. if (!subdomain && subStringEqual(inputSuffix, d, 1)) return;
  278. results.push(subdomain ? '.' + d : d);
  279. }
  280. : (suffix: string[], subdomain: boolean) => { // fast path (default option)
  281. const d = domainToASCII(fastStringArrayJoin(suffix, '.'));
  282. results.push(subdomain ? '.' + d : d);
  283. };
  284. this.walk(
  285. onMatches,
  286. false,
  287. res.node, // Performing DFS from prefix
  288. inputTokens
  289. );
  290. return results;
  291. };
  292. /**
  293. * Method used to delete a prefix from the trie.
  294. */
  295. public remove(suffix: string): boolean {
  296. const res = this.getSingleChildLeaf(hostnameToTokens(suffix, 0));
  297. if (res === null) return false;
  298. if (missingBit(res.node[0], START)) return false;
  299. this.$size--;
  300. const { node, toPrune, tokenToPrune } = res;
  301. if (tokenToPrune && toPrune) {
  302. toPrune[2].delete(tokenToPrune);
  303. } else {
  304. node[0] = deleteBit(node[0], START);
  305. }
  306. return true;
  307. };
  308. // eslint-disable-next-line @typescript-eslint/unbound-method -- safe
  309. public delete = this.remove;
  310. /**
  311. * Method used to assert whether the given prefix exists in the Trie.
  312. */
  313. public has(suffix: string, includeAllSubdomain = suffix[0] === '.'): boolean {
  314. const hostnameFromIndex = suffix[0] === '.' ? 1 : 0;
  315. const res = this.walkIntoLeafWithSuffix(suffix, hostnameFromIndex);
  316. if (res === null) return false;
  317. if (missingBit(res.node[0], START)) return false;
  318. if (includeAllSubdomain) return getBit(res.node[0], INCLUDE_ALL_SUBDOMAIN);
  319. return true;
  320. };
  321. public dumpWithoutDot(onSuffix: (suffix: string, subdomain: boolean) => void, withSort = false) {
  322. const handleSuffix = (suffix: string[], subdomain: boolean) => {
  323. onSuffix(domainToASCII(fastStringArrayJoin(suffix, '.')), subdomain);
  324. };
  325. this.walk(handleSuffix, withSort);
  326. }
  327. public dump(onSuffix: (suffix: string) => void, withSort?: boolean): void;
  328. public dump(onSuffix?: null, withSort?: boolean): string[];
  329. public dump(onSuffix?: ((suffix: string) => void) | null, withSort = false): string[] | void {
  330. const results: string[] = [];
  331. const handleSuffix = onSuffix
  332. ? (suffix: string[], subdomain: boolean) => {
  333. const d = domainToASCII(fastStringArrayJoin(suffix, '.'));
  334. onSuffix(subdomain ? '.' + d : d);
  335. }
  336. : (suffix: string[], subdomain: boolean) => {
  337. const d = domainToASCII(fastStringArrayJoin(suffix, '.'));
  338. results.push(subdomain ? '.' + d : d);
  339. };
  340. this.walk(handleSuffix, withSort);
  341. return results;
  342. };
  343. public dumpMeta(onMeta: (meta: Meta) => void, withSort?: boolean): void;
  344. public dumpMeta(onMeta?: null, withSort?: boolean): Meta[];
  345. public dumpMeta(onMeta?: ((meta: Meta) => void) | null, withSort = false): Meta[] | void {
  346. const results: Meta[] = [];
  347. const handleMeta = onMeta
  348. ? (_suffix: string[], _subdomain: boolean, meta: Meta) => onMeta(meta)
  349. : (_suffix: string[], _subdomain: boolean, meta: Meta) => results.push(meta);
  350. this.walk(handleMeta, withSort);
  351. return results;
  352. };
  353. public dumpWithMeta(onSuffix: (suffix: string, meta: Meta | undefined) => void, withSort?: boolean): void;
  354. public dumpWithMeta(onMeta?: null, withSort?: boolean): Array<[string, Meta | undefined]>;
  355. public dumpWithMeta(onSuffix?: ((suffix: string, meta: Meta | undefined) => void) | null, withSort = false): Array<[string, Meta | undefined]> | void {
  356. const results: Array<[string, Meta | undefined]> = [];
  357. const handleSuffix = onSuffix
  358. ? (suffix: string[], subdomain: boolean, meta: Meta | undefined) => {
  359. const d = domainToASCII(fastStringArrayJoin(suffix, '.'));
  360. return onSuffix(subdomain ? '.' + d : d, meta);
  361. }
  362. : (suffix: string[], subdomain: boolean, meta: Meta | undefined) => {
  363. const d = domainToASCII(fastStringArrayJoin(suffix, '.'));
  364. results.push([subdomain ? '.' + d : d, meta]);
  365. };
  366. this.walk(handleSuffix, withSort);
  367. return results;
  368. };
  369. public inspect(depth: number, unpackMeta?: (meta?: Meta) => any) {
  370. return fastStringArrayJoin(
  371. JSON.stringify(deepTrieNodeToJSON(this.$root, unpackMeta), null, 2).split('\n').map((line) => ' '.repeat(depth) + line),
  372. '\n'
  373. );
  374. }
  375. public [util.inspect.custom](depth: number) {
  376. return this.inspect(depth);
  377. };
  378. public merge(trie: Triebase<Meta>) {
  379. const handleSuffix = (suffix: string[], subdomain: boolean, meta: Meta) => {
  380. this.add(fastStringArrayJoin(suffix, '.'), subdomain, meta);
  381. };
  382. trie.walk(handleSuffix);
  383. return this;
  384. }
  385. }
  386. export class HostnameSmolTrie<Meta = unknown> extends Triebase<Meta> {
  387. public smolTree = true;
  388. add(suffix: string, includeAllSubdomain = suffix[0] === '.', meta?: Meta, hostnameFromIndex = suffix[0] === '.' ? 1 : 0): void {
  389. let node: TrieNode<Meta> = this.$root;
  390. let curNodeChildren: Map<string, TrieNode<Meta>> = node[2];
  391. const onToken = (token: string) => {
  392. curNodeChildren = node[2];
  393. if (curNodeChildren.has(token)) {
  394. node = curNodeChildren.get(token)!;
  395. // During the adding of `[start]blog|.skk.moe` and find out that there is a `[start].skk.moe` in the trie, skip adding the rest of the node
  396. if (getBit(node[0], INCLUDE_ALL_SUBDOMAIN)) {
  397. return true;
  398. }
  399. } else {
  400. const newNode = createNode(token, node);
  401. curNodeChildren.set(token, newNode);
  402. node = newNode;
  403. }
  404. return false;
  405. };
  406. // When walkHostnameTokens returns true, we should skip the rest
  407. if (walkHostnameTokens(suffix, onToken, hostnameFromIndex)) {
  408. return;
  409. }
  410. // If we are in smolTree mode, we need to do something at the end of the loop
  411. if (includeAllSubdomain) {
  412. // Trying to add `[.]sub.example.com` where there is already a `blog.sub.example.com` in the trie
  413. // Make sure parent `[start]sub.example.com` (without dot) is removed (SETINEL to false)
  414. // (/** parent */ node[2]!)[0] = false;
  415. // Removing the rest of the parent's child nodes
  416. node[2].clear();
  417. // The SENTINEL of this node will be set to true at the end of the function, so we don't need to set it here
  418. // we can use else-if here, because the children is now empty, we don't need to check the leading "."
  419. } else if (getBit(node[0], INCLUDE_ALL_SUBDOMAIN)) {
  420. // Trying to add `example.com` when there is already a `.example.com` in the trie
  421. // No need to increment size and set SENTINEL to true (skip this "new" item)
  422. return;
  423. }
  424. node[0] = setBit(node[0], START);
  425. if (includeAllSubdomain) {
  426. node[0] = setBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  427. } else {
  428. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  429. }
  430. node[4] = meta!;
  431. }
  432. public whitelist(suffix: string, includeAllSubdomain = suffix[0] === '.', hostnameFromIndex = suffix[0] === '.' ? 1 : 0) {
  433. const tokens = hostnameToTokens(suffix, hostnameFromIndex);
  434. const res = this.getSingleChildLeaf(tokens);
  435. if (res === null) return;
  436. const { node, toPrune, tokenToPrune } = res;
  437. // Trying to whitelist `[start].sub.example.com` where there might already be a `[start]blog.sub.example.com` in the trie
  438. if (includeAllSubdomain) {
  439. // If there is a `[start]sub.example.com` here, remove it
  440. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  441. // Removing all the child nodes by empty the children
  442. node[2].clear();
  443. // we do not remove sub.example.com for now, we will do that later
  444. } else {
  445. // Trying to whitelist `example.com` when there is already a `.example.com` in the trie
  446. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  447. }
  448. if (includeAllSubdomain) {
  449. node[1]?.[2].delete(node[3]);
  450. } else if (missingBit(node[0], START) && node[1]) {
  451. return;
  452. }
  453. if (toPrune && tokenToPrune) {
  454. toPrune[2].delete(tokenToPrune);
  455. } else {
  456. node[0] = deleteBit(node[0], START);
  457. }
  458. cleanUpEmptyTrailNode(node);
  459. };
  460. }
  461. function cleanUpEmptyTrailNode(node: TrieNode<unknown>) {
  462. if (
  463. // the current node is not an "end node", a.k.a. not the start of a domain
  464. missingBit(node[0], START)
  465. // also no leading "." (no subdomain)
  466. && missingBit(node[0], INCLUDE_ALL_SUBDOMAIN)
  467. // child is empty
  468. && node[2].size === 0
  469. // has parent: we need to detele the cureent node from the parent
  470. // we also need to recursively clean up the parent node
  471. && node[1]
  472. ) {
  473. node[1][2].delete(node[3]);
  474. // finish of the current stack
  475. return cleanUpEmptyTrailNode(node[1]);
  476. }
  477. }
  478. export class HostnameTrie<Meta = unknown> extends Triebase<Meta> {
  479. get size() {
  480. return this.$size;
  481. }
  482. add(suffix: string, includeAllSubdomain = suffix[0] === '.', meta?: Meta, hostnameFromIndex = suffix[0] === '.' ? 1 : 0): void {
  483. let node: TrieNode<Meta> = this.$root;
  484. let child: Map<string, TrieNode<Meta>> = node[2];
  485. const onToken = (token: string) => {
  486. child = node[2];
  487. if (child.has(token)) {
  488. node = child.get(token)!;
  489. } else {
  490. const newNode = createNode(token, node);
  491. child.set(token, newNode);
  492. node = newNode;
  493. }
  494. return false;
  495. };
  496. // When walkHostnameTokens returns true, we should skip the rest
  497. if (walkHostnameTokens(suffix, onToken, hostnameFromIndex)) {
  498. return;
  499. }
  500. // if same entry has been added before, skip
  501. if (getBit(node[0], START)) {
  502. return;
  503. }
  504. this.$size++;
  505. node[0] = setBit(node[0], START);
  506. if (includeAllSubdomain) {
  507. node[0] = setBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  508. } else {
  509. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  510. }
  511. node[4] = meta!;
  512. }
  513. }
  514. // function deepEqualArray(a: string[], b: string[]) {
  515. // let len = a.length;
  516. // if (len !== b.length) return false;
  517. // while (len--) {
  518. // if (a[len] !== b[len]) return false;
  519. // }
  520. // return true;
  521. // };
  522. function subStringEqual(needle: string, haystack: string, needleIndex = 0) {
  523. for (let i = 0, l = haystack.length; i < l; i++) {
  524. if (needle[i + needleIndex] !== haystack[i]) return false;
  525. }
  526. return true;
  527. }