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