foxts
Version:
Opinionated collection of common TypeScript utils by @SukkaW
23 lines • 1.53 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 e(e,n,t){if(t<0||!Number.isSafeInteger(t))return;if(""===n)return e[t];let i=0;for(let r=0;r<t;r++){const t=e.indexOf(n,i);if(-1===t)return;i=t+n.length}const r=e.indexOf(n,i);return -1===r?e.slice(i):e.slice(i,r)}function n(e,n){const t=e.indexOf(n);return -1===t?e:e.slice(0,t)}function t(e,n){const t=e.indexOf(n);if(-1===t)return;const i=t+n.length,r=e.indexOf(n,i);return -1===r?e.slice(i):e.slice(i,r)}export{n as splitFirst,e as splitNth,t as splitSecond};