Untitled

 avatar
unknown
plain_text
a year ago
1.4 kB
6
Indexable
function split(data: string, {sep = null, maxsplit = -1}: {sep?: string | null, maxsplit?: number} = {}): string[] {
    const separator = sep === null ? [' '] : sep.split('');
    const result: string[] = []

    let sepIndex = 0;
    let sepLastIndex = separator.length - 1;

    let curr = ''
    let splitted = 0;

    function resetSepIndex() {
        sepIndex = 0;
    }

    function checkChar(char: string) {
        if (char === separator[sepIndex]) {
            if (sepLastIndex === sepIndex) {
                resetSepIndex();

                return { sep: true, last: true };
            }

            sepIndex += 1;

            return { sep: true, last: false };
        }

        resetSepIndex();

        return { sep: false, last: false };
    }

    function doChar(char: string) {
        if (maxsplit > -1 && splitted >= maxsplit) {
            curr += char;

            return;
        } 

        const { sep, last } = checkChar(char);

        if (!sep) {
            curr += char;
        }

        if (last) {
            result.push(curr);

            splitted += 1;

            curr = '';
        }
    } 

    for (const char of data) {
        if (char === ' ') {
            if (curr !== '') {
                doChar(char)
            }
        } else {
            doChar(char)
        }
    }

    result.push(curr)

    return result
}
Editor is loading...
Leave a Comment