Вот функциональная кодировка, которая работает для любого повторяемого ввода (включая массивы)
const None =
Symbol ()
const prepend = (xs, x) =>
[ x ] .concat (xs)
const split = (f, [ x = None, ...xs ], then = prepend) =>
x === None
? then ([], [])
: split
( f
, xs
, (l, r) =>
f (x)
? then (prepend (l, r), [])
: then (l, prepend (r, x))
)
const data =
[ 'something', 'else', 'and', 'd', 'more', 'things', 'in', 'the', 'd', 'array', 'etc' ]
console .log
( split (x => x === 'd', data)
)
// [ [ 'something', 'else', 'and' ]
// , [ 'more', 'things', 'in', 'the' ]
// , [ 'array', 'etc' ]
// ]
И оптимизация, которая работает для любого массива input
const prepend = (xs, x) =>
[ x ] .concat (xs)
const split = (f, xs = [], i = 0, then = prepend) =>
i >= xs.length
? then ([], [])
: split
( f
, xs
, i + 1
, (l, r) =>
f (xs[i])
? then (prepend (l, r), [])
: then (l, prepend (r, xs[i]))
)
const data =
[ 'something', 'else', 'and', 'd', 'more', 'things', 'in', 'the', 'd', 'array', 'etc' ]
console .log
( split (x => x === 'd', data)
)
// [ [ 'something', 'else', 'and' ]
// , [ 'more', 'things', 'in', 'the' ]
// , [ 'array', 'etc' ]
// ]
Обе реализации O (n) .