use crate::runner::ds::error::JErrorType;
use crate::runner::ds::value::JsValue;
use crate::runner::plugin::registry::BuiltInRegistry;
use crate::runner::plugin::types::{BuiltInObject, EvalContext};
pub fn register(registry: &mut BuiltInRegistry) {
let object = BuiltInObject::new("Object")
.with_no_prototype()
.with_constructor(object_constructor)
.add_method("toString", object_to_string)
.add_method("valueOf", object_value_of)
.add_method("hasOwnProperty", object_has_own_property)
.add_method("keys", object_keys)
.add_method("values", object_values)
.add_method("entries", object_entries)
.add_method("assign", object_assign);
registry.register_object(object);
}
fn object_constructor(
_ctx: &mut EvalContext,
_this: JsValue,
args: Vec<JsValue>,
) -> Result<JsValue, JErrorType> {
if args.is_empty() {
Ok(JsValue::Undefined)
} else {
let arg = &args[0];
match arg {
JsValue::Null | JsValue::Undefined => {
Ok(JsValue::Undefined)
}
JsValue::Object(_) => {
Ok(arg.clone())
}
_ => {
Ok(arg.clone())
}
}
}
}
fn object_to_string(
_ctx: &mut EvalContext,
this: JsValue,
_args: Vec<JsValue>,
) -> Result<JsValue, JErrorType> {
let tag = match &this {
JsValue::Undefined => "Undefined",
JsValue::Null => "Null",
JsValue::Boolean(_) => "Boolean",
JsValue::Number(_) => "Number",
JsValue::String(_) => "String",
JsValue::Symbol(_) => "Symbol",
JsValue::Object(_) => "Object",
};
Ok(JsValue::String(format!("[object {}]", tag)))
}
fn object_value_of(
_ctx: &mut EvalContext,
this: JsValue,
_args: Vec<JsValue>,
) -> Result<JsValue, JErrorType> {
Ok(this)
}
fn object_has_own_property(
_ctx: &mut EvalContext,
_this: JsValue,
args: Vec<JsValue>,
) -> Result<JsValue, JErrorType> {
if args.is_empty() {
return Ok(JsValue::Boolean(false));
}
Ok(JsValue::Boolean(false))
}
fn object_keys(
_ctx: &mut EvalContext,
_this: JsValue,
args: Vec<JsValue>,
) -> Result<JsValue, JErrorType> {
if args.is_empty() {
return Err(JErrorType::TypeError(
"Cannot convert undefined or null to object".to_string(),
));
}
Ok(JsValue::Undefined)
}
fn object_values(
_ctx: &mut EvalContext,
_this: JsValue,
args: Vec<JsValue>,
) -> Result<JsValue, JErrorType> {
if args.is_empty() {
return Err(JErrorType::TypeError(
"Cannot convert undefined or null to object".to_string(),
));
}
Ok(JsValue::Undefined)
}
fn object_entries(
_ctx: &mut EvalContext,
_this: JsValue,
args: Vec<JsValue>,
) -> Result<JsValue, JErrorType> {
if args.is_empty() {
return Err(JErrorType::TypeError(
"Cannot convert undefined or null to object".to_string(),
));
}
Ok(JsValue::Undefined)
}
fn object_assign(
_ctx: &mut EvalContext,
_this: JsValue,
args: Vec<JsValue>,
) -> Result<JsValue, JErrorType> {
if args.is_empty() {
return Err(JErrorType::TypeError(
"Cannot convert undefined or null to object".to_string(),
));
}
Ok(args[0].clone())
}