trie.ts 20 KB

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