Skip to content

Instantly share code, notes, and snippets.

@j0sh
Created July 31, 2023 21:22
Show Gist options
  • Save j0sh/7f112d6910415aabb4a366cba0090d7c to your computer and use it in GitHub Desktop.
Save j0sh/7f112d6910415aabb4a366cba0090d7c to your computer and use it in GitHub Desktop.
typescript string split with remainder
import { split } from './utils';
test('string split', () => {
const p = split("a b c d", " ", 2);
expect(p).toStrictEqual(["a", "b c d"]);
});
test('string split nonexistent', () => {
const p = split("a b c d", ",", 2);
expect(p).toStrictEqual(["a b c d"]);
});
test('string split under max', () => {
const p = split("a b c d", " ", 10);
expect(p).toStrictEqual(["a", "b", "c", "d"]);
});
test('string split at max', () => {
const p = split("a b c d", " ", 4);
expect(p).toStrictEqual(["a", "b", "c", "d"]);
});
test('string split with trailing', () => {
const p = split("a b c d ", " ", 2);
expect(p).toStrictEqual(["a", "b c d "]);
});
test('string split with trailing at max', () => {
const p = split("a b c d ", " ", 4);
expect(p).toStrictEqual(["a", "b", "c", "d "]);
});
test('string split with trailing beyond max', () => {
const p = split("a b c d ", " ", 10);
expect(p).toStrictEqual(["a", "b", "c", "d"]);
});
test('string split with removed redundant separators', () => {
const p = split("a b c d ", " ", 5);
expect(p).toStrictEqual(["a", "b", "c", "d"]);
});
test('string split with removed redundant separators', () => {
const p = split("a b c d ", " ", 10);
expect(p).toStrictEqual(["a", "b", "c", "d"]);
});
test('string split with removed redundant separators 2', () => {
const p = split("a b c d ", " ", 4);
expect(p).toStrictEqual(["a", "b", "c", "d "]);
});
// string split that preserves the remainder
export function split(str: string, separator: string, limit: number): string[] {
const result: string[] = [];
let lastIndex = 0;
let count = 0;
while (count < limit - 1) {
const index = str.indexOf(separator, lastIndex);
if (index === -1) break;
const substr = str.slice(lastIndex, index);
if (substr !== "") {
result.push(substr);
count++;
}
lastIndex = index + separator.length;
}
// trim any leading separators from the last element
const remaining = str.slice(lastIndex).replace(new RegExp("^"+separator+"+", "i"), "");
if (remaining !== "") {
result.push(remaining);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment