const str = "The quick brown fox jumps over the lazy dog.\n".repeat(100) function fold_parts(str, sep, state, fun) { let position = 0 while (true) { let idx = str.indexOf(sep, position) if (idx < 0) { return fun(state, str.slice(position)) } state = fun(state, str.slice(position, idx)) position = idx + sep.length } } let sum = 0 for(let i = 0; i < 1000000; ++i) { sum += fold_parts(str, '\n', 0, (acc, line) => acc + line.length) } console.log(sum)