Skip to content

Commit

Permalink
ZipLongest::rfold
Browse files Browse the repository at this point in the history
  • Loading branch information
Philippe-Cholet committed Jan 13, 2024
1 parent 5a321ca commit d003359
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/zip_longest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,37 @@ where
Less => self.b.next_back().map(EitherOrBoth::Right),
}
}

fn rfold<B, F>(self, mut init: B, mut f: F) -> B
where
F: FnMut(B, Self::Item) -> B,
{
let Self { mut a, mut b } = self;
let a_len = a.len();
let b_len = b.len();
match a_len.cmp(&b_len) {
Equal => {}
Greater => {
init = a
.by_ref()
.rev()
.take(a_len - b_len)
.map(EitherOrBoth::Left)
.fold(init, &mut f)
}
Less => {
init = b
.by_ref()
.rev()
.take(b_len - a_len)
.map(EitherOrBoth::Right)
.fold(init, &mut f)
}
}
a.rfold(init, |acc, item_a| {
f(acc, EitherOrBoth::Both(item_a, b.next_back().unwrap()))
})
}
}

impl<T, U> ExactSizeIterator for ZipLongest<T, U>
Expand Down

0 comments on commit d003359

Please sign in to comment.