Split an array into kept items and a trailing matching run
A voice-memo app trims the silence at the end of every recording. It cannot simply delete it, though: the editor shows the trimmed tail greyed out so the user can undo the trim. So instead of only dropping the trailing run, you need both halves.
Implement splitTrailing(items, predicate). It finds the longest run at the end of items where every element satisfies predicate, and returns [kept, trailing]: the elements before that run, and the run itself.
splitTrailing(items, predicate) // => [kept, trailing]
predicate(value, index, items) starting from the last element and moving towards the first. Stop at the first element for which it returns a falsy value. That element, and everything before it, goes into kept.predicate again after it returns a falsy value, and never call it more than once per element.true.kept.concat(trailing) equals items.items.splitTrailing([0, 1, 0, 0], isZero) gives [[0, 1], [0, 0]].const samples = [0.4, 0.9, 0.02, 0.6, 0.01, 0, 0.03];
const isSilent = (level) => level < 0.05;
splitTrailing(samples, isSilent);
// => [[0.4, 0.9, 0.02, 0.6], [0.01, 0, 0.03]]
splitTrailing([1, 2, 3], (n) => n > 5); // => [[1, 2, 3], []]
splitTrailing([7, 8], (n) => n > 5); // => [[], [7, 8]]
splitTrailing([], (n) => n > 5); // => [[], []]
const lines = ['Notes', '- buy milk', '', ' '];
splitTrailing(lines, (line, index) => index > 0 && line.trim() === '');
// => [['Notes', '- buy milk'], ['', ' ']]