newline-iterator
Version:
Line-by-line string iterator
67 lines (63 loc) • 2.17 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.newlineIterator = factory());
})(this, (function () { 'use strict';
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var REGEX_NEW_LINE = /\r?\n|\r/g;
var root = typeof window === 'undefined' ? global : window;
// biome-ignore lint/suspicious/noShadowRestrictedNames: Legacy
var 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"];
* ```
*/ function newlineIterator(string) {
var lines = string.split(REGEX_NEW_LINE).reverse();
var iterator = _define_property({
next: function next() {
if (lines.length === 0) return {
value: null,
done: true
};
var value = lines.pop();
if (lines.length === 0 && value.length === 0) return {
value: null,
done: true
};
return {
value: value,
done: false
};
}
}, Symbol.iterator, function() {
return this;
});
return iterator;
}
return newlineIterator;
}));
//# sourceMappingURL=newline-iterator.cjs.map