foxts
Version:
Opinionated collection of common TypeScript utils by @SukkaW
23 lines • 1.58 kB
JavaScript
/**
* Get the `index`-th segment of `str.split(sep)` without creating the
* intermediate array, using `String.prototype.indexOf` and `String.prototype.slice`.
*
* Matches `str.split(sep)[index]` behavior (string separator only, no regex):
*
* - `splitNth('a,b', ',', 5)` returns `undefined` (out of range)
* - `splitNth('', ',', 0)` returns `''` (`''.split(',')` is `['']`)
* - `splitNth('abc', '', 1)` returns `'b'` (empty separator splits into UTF-16 code units)
* - `splitNth('', '', 0)` returns `undefined` (`''.split('')` is `[]`)
*
* @example
* ```ts
* splitNth('foo\nbar\nbaz', '\n', 0); // 'foo', same as 'foo\nbar\nbaz'.split('\n')[0]
* splitNth('foo\nbar\nbaz', '\n', 2); // 'baz'
* ```
*
* On a 64-line (~2 KB) string (see `index.bench.ts`): ~5x faster than
* `split(sep, 1)[0]` and ~110x faster than `split(sep)[0]`; ~2x / ~28x for
* `[2]`; ~1.6x for the last segment, allocating 0 bytes vs ~2.5 KB per call.
* The win shrinks as `index` grows, since cost is proportional to how deep
* into the string the segment sits.
*/function t(t,n,e){if(e<0||!Number.isSafeInteger(e))return;if(""===n)return t[e];let i=0;for(let s=0;s<e;s++){const e=t.indexOf(n,i);if(-1===e)return;i=e+n.length}const s=t.indexOf(n,i);return -1===s?t.slice(i):t.slice(i,s)}function n(t,n){const e=t.indexOf(n);return -1===e?t:t.slice(0,e)}const e=n;function i(t,n){const e=t.indexOf(n);if(-1===e)return;const i=e+n.length,s=t.indexOf(n,i);return -1===s?t.slice(i):t.slice(i,s)}const s=i;export{e as split0th,s as split1st,n as splitFirst,t as splitNth,i as splitSecond};