|
| 1 | +use crate::value::{Object, Value}; |
| 2 | + |
| 3 | +pub fn scope() -> Object { |
| 4 | + let scope = Object::new(); |
| 5 | + let std = Object::new(); |
| 6 | + |
| 7 | + std.set("len", Value::rust_function(|_ctx, args| { |
| 8 | + match args.get(0) { |
| 9 | + Some(Value::Array(arr)) => Ok(Value::Number(arr.len() as f64)), |
| 10 | + Some(Value::Object(obj)) => Ok(Value::Number(obj.len() as f64)), |
| 11 | + _ => Err(Value::string("invalid argument")), |
| 12 | + } |
| 13 | + })); |
| 14 | + |
| 15 | + std.set("iter", Value::rust_function(|_ctx, args| { |
| 16 | + match args.get(0) { |
| 17 | + Some(Value::Array(arr)) => { |
| 18 | + let iter = Object::new(); |
| 19 | + let iter_clone = iter.clone(); |
| 20 | + // TODO: Can `args` be destructured to prevent this clone? |
| 21 | + let arr = arr.clone(); |
| 22 | + |
| 23 | + // TODO: Use internal object value for this: |
| 24 | + iter.set("_index", Value::Number(0.0)); |
| 25 | + |
| 26 | + // TODO: Bad news, gamers. https://github.com/Manishearth/rust-gc/issues/50 |
| 27 | + iter.set("next", Value::rust_function(move |_ctx, _args| { |
| 28 | + let next = Object::new(); |
| 29 | + let index = match iter_clone.get("_index") { |
| 30 | + Some(Value::Number(number)) => number as usize, |
| 31 | + _ => panic!("TODO: Use internal object value for this"), |
| 32 | + }; |
| 33 | + if let Some(value) = arr.get(index) { |
| 34 | + iter_clone.set("_index", Value::Number((index + 1) as f64)); |
| 35 | + next.set("value", value); |
| 36 | + } else { |
| 37 | + next.set("done", Value::Boolean(true)); |
| 38 | + } |
| 39 | + Ok(Value::Object(next)) |
| 40 | + })); |
| 41 | + |
| 42 | + Ok(Value::Object(iter)) |
| 43 | + }, |
| 44 | + _ => Err(Value::string("invalid argument")), |
| 45 | + } |
| 46 | + })); |
| 47 | + |
| 48 | + scope.set("std", Value::Object(std)); |
| 49 | + scope |
| 50 | +} |
0 commit comments