UNPKG

newline-iterator

Version:
44 lines (43 loc) 1.33 kB
const REGEX_NEW_LINE = /\r?\n|\r/g; const root = typeof window === 'undefined' ? global : window; // biome-ignore lint/suspicious/noShadowRestrictedNames: Legacy const Symbol = typeof root.Symbol === 'undefined' ? { iterator: undefined } : root.Symbol; /** * Create a newline iterator recognizing CR, LF, and CRLF using the Symbol.iterator interface * * @param string The string to iterate through * * ```typescript * import newlineIterator from "newline-iterator"; * * const iterator = newlineIterator("some\r\nstring\ncombination\r"); * const results = []; * for (const line of iterator) results.push(line); * console.log(results); // ["some", "string", "combination"]; * ``` */ export default function newlineIterator(string) { const lines = string.split(REGEX_NEW_LINE).reverse(); const iterator = { next () { if (lines.length === 0) return { value: null, done: true }; const value = lines.pop(); if (lines.length === 0 && value.length === 0) return { value: null, done: true }; return { value, done: false }; }, [Symbol.iterator] () { return this; } }; return iterator; }