Add array prototype

This commit is contained in:
Andrew Morris
2022-05-20 10:54:05 +10:00
parent b5989a8137
commit ca5ef43ee2
2 changed files with 52 additions and 4 deletions

View File

@@ -259,12 +259,12 @@ pub fn op_sub(left: Val, right: Val) -> Val {
},
Val::Array(array_data) => {
let right_index = match right.to_index() {
None => { return Val::Undefined }
None => { return array_data.object.sub(right) }
Some(i) => i,
};
if right_index >= array_data.elements.len() {
return array_data.object.sub(right);
return Val::Undefined;
}
let res = array_data.elements[right_index].clone();

View File

@@ -1,4 +1,13 @@
use super::vs_value::Val;
use std::rc::Rc;
use super::vs_value::{
Val,
VsType,
ValTrait,
StaticValExtraTrait,
StaticValTrait,
LoadFunctionResult,
};
use super::vs_object::VsObject;
#[derive(Clone)]
@@ -11,7 +20,46 @@ impl VsArray {
pub fn from(vals: Vec<Val>) -> VsArray {
return VsArray {
elements: vals,
object: VsObject::default(),
object: VsObject {
string_map: Default::default(),
prototype: Some(Val::Static(&ARRAY_PROTOTYPE)),
},
};
}
}
pub struct ArrayPrototype {}
static ARRAY_PROTOTYPE: ArrayPrototype = ArrayPrototype {};
impl ValTrait for ArrayPrototype {
fn typeof_(&self) -> VsType { VsType::Object }
fn val_to_string(&self) -> String { "".to_string() }
fn to_number(&self) -> f64 { 0_f64 }
fn to_index(&self) -> Option<usize> { None }
fn is_primitive(&self) -> bool { false }
fn to_primitive(&self) -> Val { Val::String(Rc::new("".to_string())) }
fn is_truthy(&self) -> bool { true }
fn is_nullish(&self) -> bool { false }
fn resolve(&self) -> Val { Val::Static(&ARRAY_PROTOTYPE) }
fn bind(&self, _params: Vec<Val>) -> Option<Val> { None }
fn as_array_data(&self) -> Option<Rc<VsArray>> { None }
fn as_object_data(&self) -> Option<Rc<VsObject>> { None }
fn load_function(&self) -> LoadFunctionResult {
LoadFunctionResult::NotAFunction
}
}
impl StaticValExtraTrait for ArrayPrototype {
fn sub(&self, key: Val) -> Val {
match key.val_to_string().as_str() {
_ => Val::Undefined,
}
}
}
impl StaticValTrait for ArrayPrototype {}