serde_json_lodash/array/initial.rs
1use crate::lib::{json, Value};
2
3/// See lodash [initial](https://lodash.com/docs/#initial)
4pub fn initial(v: Value) -> Value {
5 match v {
6 Value::Null => json!([]),
7 Value::Bool(_) => json!([]),
8 Value::String(s) => {
9 let mut vec = s.chars().map(|x| json!(x)).collect::<Vec<Value>>();
10 if vec.len() <= 1 {
11 return json!([]);
12 }
13 vec.pop();
14 Value::Array(vec)
15 }
16 Value::Number(_) => json!([]),
17 Value::Array(mut vec) => {
18 if vec.len() <= 1 {
19 return json!([]);
20 }
21 vec.pop();
22 Value::Array(vec)
23 }
24 Value::Object(_) => json!([]),
25 }
26}
27
28/// Based on [initial()]
29///
30/// Examples:
31///
32/// ```rust
33/// #[macro_use] extern crate serde_json_lodash;
34/// use serde_json::json;
35/// assert_eq!(
36/// initial!(json!([1, 2, 3])),
37/// json!([1, 2])
38/// );
39/// ```
40///
41/// More examples:
42///
43/// ```rust
44/// # #[macro_use] extern crate serde_json_lodash;
45/// # use serde_json::json;
46/// assert_eq!(initial!(), json!([]));
47/// assert_eq!(initial!(json!(null)), json!([]));
48/// assert_eq!(initial!(json!(false)), json!([]));
49/// assert_eq!(initial!(json!(0)), json!([]));
50/// assert_eq!(initial!(json!("")), json!([]));
51/// assert_eq!(initial!(json!("abc")), json!(["a","b"]));
52/// assert_eq!(initial!(json!("日本国")), json!(["日","本"]));
53/// assert_eq!(initial!(json!({})), json!([]));
54/// assert_eq!(initial!(json!({"a":1})), json!([]));
55/// ```
56#[macro_export]
57macro_rules! initial {
58 () => {
59 json!([])
60 };
61 ($a:expr $(,)*) => {
62 $crate::initial($a)
63 };
64 ($a:expr, $($rest:tt)*) => {
65 $crate::initial($a)
66 };
67}