-
Notifications
You must be signed in to change notification settings - Fork 77
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(stdlib): Add new
object_from_array
function
- Loading branch information
Showing
4 changed files
with
145 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
Added new `object_from_array` function to create an object from an array of | ||
value pairs such as what `zip` can produce. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
use crate::compiler::prelude::*; | ||
|
||
fn make_object(values: Vec<Value>) -> Resolved { | ||
values | ||
.into_iter() | ||
.map(make_key_value) | ||
.collect::<Result<_, _>>() | ||
.map(Value::Object) | ||
} | ||
|
||
fn make_key_value(value: Value) -> Result<(KeyString, Value), ExpressionError> { | ||
value.try_array().map_err(Into::into).and_then(|array| { | ||
let mut iter = array.into_iter(); | ||
let key: KeyString = match iter.next() { | ||
None => return Err("array value too short".into()), | ||
Some(Value::Bytes(key)) => String::from_utf8_lossy(&key).into(), | ||
Some(_) => return Err("object keys must be strings".into()), | ||
}; | ||
let value = iter.next().unwrap_or(Value::Null); | ||
Ok((key, value)) | ||
}) | ||
} | ||
|
||
#[derive(Clone, Copy, Debug)] | ||
pub struct ObjectFromArray; | ||
|
||
impl Function for ObjectFromArray { | ||
fn identifier(&self) -> &'static str { | ||
"object_from_array" | ||
} | ||
|
||
fn parameters(&self) -> &'static [Parameter] { | ||
&[Parameter { | ||
keyword: "values", | ||
kind: kind::ARRAY, | ||
required: true, | ||
}] | ||
} | ||
|
||
fn examples(&self) -> &'static [Example] { | ||
&[Example { | ||
title: "create an object from an array of keys/value pairs", | ||
source: r#"object_from_array([["a", 1], ["b"], ["c", true, 3, 4]])"#, | ||
result: Ok(r#"{"a": 1, "b": null, "c": true}"#), | ||
}] | ||
} | ||
|
||
fn compile( | ||
&self, | ||
state: &TypeState, | ||
_ctx: &mut FunctionCompileContext, | ||
arguments: ArgumentList, | ||
) -> Compiled { | ||
let values = ConstOrExpr::new(arguments.required("values"), state); | ||
|
||
Ok(OFAFn { values }.as_expr()) | ||
} | ||
} | ||
|
||
#[derive(Clone, Debug)] | ||
struct OFAFn { | ||
values: ConstOrExpr, | ||
} | ||
|
||
impl FunctionExpression for OFAFn { | ||
fn resolve(&self, ctx: &mut Context) -> Resolved { | ||
make_object(self.values.resolve(ctx)?.try_array()?) | ||
} | ||
|
||
fn type_def(&self, _state: &TypeState) -> TypeDef { | ||
TypeDef::object(Collection::any()) | ||
} | ||
} | ||
|
||
#[derive(Clone, Debug)] | ||
enum ConstOrExpr { | ||
Const(Value), | ||
Expr(Box<dyn Expression>), | ||
} | ||
|
||
impl ConstOrExpr { | ||
fn new(expr: Box<dyn Expression>, state: &TypeState) -> Self { | ||
match expr.resolve_constant(state) { | ||
Some(cnst) => Self::Const(cnst), | ||
None => Self::Expr(expr), | ||
} | ||
} | ||
|
||
fn resolve(&self, ctx: &mut Context) -> Resolved { | ||
match self { | ||
Self::Const(value) => Ok(value.clone()), | ||
Self::Expr(expr) => expr.resolve(ctx), | ||
} | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use crate::value; | ||
|
||
use super::*; | ||
|
||
test_function![ | ||
object_from_array => ObjectFromArray; | ||
|
||
makes_object_simple { | ||
args: func_args![values: value!([["foo", 1], ["bar", 2]])], | ||
want: Ok(value!({"foo": 1, "bar": 2})), | ||
tdef: TypeDef::object(Collection::any()), | ||
} | ||
|
||
handles_missing_values { | ||
args: func_args![values: value!([["foo", 1], ["bar"]])], | ||
want: Ok(value!({"foo": 1, "bar": null})), | ||
tdef: TypeDef::object(Collection::any()), | ||
} | ||
|
||
drops_extra_values { | ||
args: func_args![values: value!([["foo", 1, 2, 3, 4]])], | ||
want: Ok(value!({"foo": 1})), | ||
tdef: TypeDef::object(Collection::any()), | ||
} | ||
|
||
errors_on_missing_keys { | ||
args: func_args![values: value!([["foo", 1], []])], | ||
want: Err("array value too short"), | ||
tdef: TypeDef::object(Collection::any()), | ||
} | ||
]; | ||
} |