MCPcopy Index your code
hub / github.com/aiscriptdev/aiscript / filter

Function filter

aiscript-vm/src/builtins/function.rs:53–103  ·  view source on GitHub ↗
(
    state: &mut State<'gc>,
    args: Vec<Value<'gc>>,
)

Source from the content-addressed store, hash-verified

51}
52
53pub(super) fn filter<'gc>(
54 state: &mut State<'gc>,
55 args: Vec<Value<'gc>>,
56) -> Result<Value<'gc>, VmError> {
57 if args.len() != 2 {
58 return Err(VmError::RuntimeError(
59 "filter() takes exactly 2 arguments.".into(),
60 ));
61 }
62
63 // Get the iterable
64 let vec = match &args[0] {
65 Value::List(list) => &list.borrow().data,
66 _ => {
67 return Err(VmError::RuntimeError(
68 "filter() first argument must be an array.".into(),
69 ));
70 }
71 };
72
73 // Get the function id
74 let function = match args[1] {
75 Value::Closure(ref f) => f.function,
76 Value::NativeFunction(_) => {
77 return Err(VmError::RuntimeError(
78 "filter() doesn't support native functions yet.".into(),
79 ));
80 }
81 _ => {
82 return Err(VmError::RuntimeError(
83 "filter() second argument must be a function.".into(),
84 ));
85 }
86 };
87
88 // Create result array
89 let mut result = Vec::with_capacity(vec.len());
90
91 // Filter elements based on predicate function
92 for value in vec.iter() {
93 // Prepare arguments for the function call
94 let call_args = vec![*value];
95
96 // Call function and check if it returns true
97 if state.eval_function(function, &call_args)?.is_true() {
98 result.push(*value);
99 }
100 }
101
102 Ok(Value::array(state, result))
103}
104
105pub(super) fn zip<'gc>(
106 state: &mut State<'gc>,

Callers

nothing calls this directly

Calls 6

RuntimeErrorClass · 0.85
lenMethod · 0.80
is_trueMethod · 0.80
pushMethod · 0.80
borrowMethod · 0.45
eval_functionMethod · 0.45

Tested by

no test coverage detected