From 88e6dcdb73c4a8caa5c43d264eb329860d4b3287 Mon Sep 17 00:00:00 2001 From: GrayJack Date: Fri, 12 Apr 2024 00:40:36 -0300 Subject: [PATCH] feat(array): Add `JanetArray::pop_if` --- src/types/array.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/types/array.rs b/src/types/array.rs index 415d602a20..59c944f327 100644 --- a/src/types/array.rs +++ b/src/types/array.rs @@ -350,6 +350,32 @@ impl<'data> JanetArray<'data> { } } + /// Removes and returns the last element in a vector if the predicate + /// returns `true`, or [`None`] if the predicate returns false or the vector + /// is empty. + /// + /// # Examples + /// + /// ``` + /// use janetrs::{array, DeepEq, Janet, JanetArray}; + /// # let _client = janetrs::client::JanetClient::init().unwrap(); + /// + /// let mut array = array![1, 2, 3, 4]; + /// let pred = |x: &mut Janet| match x.try_unwrap::() { + /// Ok(x) => x % 2 == 0, + /// Err(_) => false, + /// }; + /// + /// assert_eq!(array.pop_if(pred), Some(Janet::from(4))); + /// assert!(array.deep_eq(&array![1, 2, 3])); + /// assert_eq!(array.pop_if(pred), None); + /// ``` + pub fn pop_if(&mut self, f: F) -> Option + where F: FnOnce(&mut Janet) -> bool { + let last = self.last_mut()?; + if f(last) { self.pop() } else { None } + } + /// Returns a copy of the last element in the array without modifying it. /// /// # Examples @@ -2779,6 +2805,24 @@ mod tests { Ok(()) } + #[test] + fn pop_if() -> Result<(), crate::client::Error> { + let _client = JanetClient::init()?; + + + let mut array = array![1, 2, 3, 4]; + let pred = |x: &mut Janet| match x.try_unwrap::() { + Ok(x) => x % 2 == 0, + Err(_) => false, + }; + + assert_eq!(array.pop_if(pred), Some(Janet::from(4))); + assert!(array.deep_eq(&array![1, 2, 3])); + assert_eq!(array.pop_if(pred), None); + + Ok(()) + } + #[test] fn set_length() -> Result<(), crate::client::Error> { let _client = JanetClient::init()?;