UNPKG

foxts

Version:

Opinionated collection of common TypeScript utils by @SukkaW

23 lines 1.58 kB
"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. */function t(t,e){const n=t.indexOf(e);return -1===n?t:t.slice(0,n)}function e(t,e){const n=t.indexOf(e);if(-1===n)return;const i=n+e.length,s=t.indexOf(e,i);return -1===s?t.slice(i):t.slice(i,s)}exports.split0th=t,exports.split1st=e,exports.splitFirst=t,exports.splitNth=function(t,e,n){if(n<0||!Number.isSafeInteger(n))return;if(""===e)return t[n];let i=0;for(let s=0;s<n;s++){const n=t.indexOf(e,i);if(-1===n)return;i=n+e.length}const s=t.indexOf(e,i);return -1===s?t.slice(i):t.slice(i,s)},exports.splitSecond=e;