serde_json_lodash/array/pull_all_by.rs
1use crate::lib::{Value};
2
3/// See lodash [pullAllBy](https://lodash.com/docs/#pullAllBy)
4pub fn pull_all_by(mut array: Value, values: Value, iteratee: fn(&Value) -> &Value) -> Value {
5 let new_vec = match array {
6 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) | Value::Object(_) => {
7 return array
8 }
9 Value::Array(ref vec) => {
10 let values_vec = match values {
11 Value::Null
12 | Value::Bool(_)
13 | Value::Number(_)
14 | Value::String(_)
15 | Value::Object(_) => return array,
16 Value::Array(vec) => vec,
17 };
18 let mut new_vec = vec![];
19 'a: for item in vec.iter() {
20 let id_item = iteratee(item);
21 for value in values_vec.iter() {
22 let id_value = iteratee(value);
23 if id_item == id_value {
24 continue 'a;
25 }
26 }
27 new_vec.push(item.clone())
28 }
29 new_vec
30 }
31 };
32 *array.as_array_mut().unwrap() = new_vec;
33 array
34}
35
36/// Based on [pull_all_by()]
37///
38/// Examples:
39///
40/// ```rust
41/// #[macro_use] extern crate serde_json_lodash;
42/// use serde_json::json;
43/// let array = json!([{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]);
44/// // conflict with fn, not implemented
45/// // assert_eq!(
46/// // pull_all_by!(array, json!([{ 'x': 1 }, { 'x': 3 }]), "x"),
47/// // json!(0)
48/// // );
49/// assert_eq!(
50/// pull_all_by!(array, json!([{ 'x': 1 }, { 'x': 3 }]), |o| &o["x"]),
51/// json!([{ 'x': 2 }])
52/// );
53/// ```
54///
55/// More examples:
56///
57/// ```rust
58/// # #[macro_use] extern crate serde_json_lodash;
59/// # use serde_json::json;
60/// assert_eq!(pull_all_by!(), json!(null));
61/// assert_eq!(pull_all_by!(json!(null)), json!(null));
62/// assert_eq!(pull_all_by!(json!(false)), json!(false));
63/// assert_eq!(pull_all_by!(json!(0)), json!(0));
64/// assert_eq!(pull_all_by!(json!("")), json!(""));
65/// assert_eq!(pull_all_by!(json!([])), json!([]));
66/// assert_eq!(pull_all_by!(json!([[]]), json!([])), json!([[]]));
67/// assert_eq!(pull_all_by!(json!([{}]), json!({})), json!([{}]));
68/// assert_eq!(pull_all_by!(json!([null]), json!([null])), json!([]));
69/// assert_eq!(pull_all_by!(json!([null,0]), json!([null]), |x| &x), json!([0]));
70/// assert_eq!(pull_all_by!(json!([null,0]), json!([null]), |x| &x["__non__"]), json!([]));
71/// assert_eq!(pull_all_by!(json!({})), json!({}));
72/// ```
73#[macro_export]
74macro_rules! pull_all_by {
75 () => {
76 json!(null)
77 };
78 ($a:expr $(,)*) => {
79 $a
80 };
81 ($a:expr, $b:expr $(,)*) => {
82 $crate::pull_all($a, $b)
83 };
84 ($a:expr, $b:expr, $c:expr $(,)*) => {
85 $crate::pull_all_by($a, $b, $c)
86 };
87 ($a:expr, $b:expr, $c:expr, $($rest:tt)*) => {
88 $crate::pull_all_by($a, $b, $c)
89 };
90}