mirror of
https://github.com/voltrevo/ValueScript.git
synced 2026-01-14 07:57:57 -05:00
to_primitive
This commit is contained in:
@@ -1,12 +1,16 @@
|
||||
use super::vs_value::Val;
|
||||
use super::vs_value::ValTrait;
|
||||
use super::vs_value::VsType;
|
||||
use super::vs_string::VsString;
|
||||
use super::vs_number::VsNumber;
|
||||
|
||||
pub fn op_plus(left: &Val, right: &Val) -> Val {
|
||||
if left.typeof_() == VsType::String || right.typeof_() == VsType::String {
|
||||
return VsString::from_string(left.to_string() + &right.to_string());
|
||||
let left_prim = left.to_primitive();
|
||||
let right_prim = right.to_primitive();
|
||||
|
||||
if left_prim.typeof_() == VsType::String || right_prim.typeof_() == VsType::String {
|
||||
return VsString::from_string(left_prim.to_string() + &right_prim.to_string());
|
||||
}
|
||||
|
||||
return VsNumber::from_f64(left.to_number() + right.to_number());
|
||||
return VsNumber::from_f64(left_prim.to_number() + right_prim.to_number());
|
||||
}
|
||||
|
||||
@@ -26,4 +26,8 @@ impl VsValue for VsNumber {
|
||||
fn to_number(&self) -> f64 {
|
||||
return self.value;
|
||||
}
|
||||
|
||||
fn is_primitive(&self) -> bool {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,4 +75,17 @@ impl VsValue for VsPointer {
|
||||
fn to_number(&self) -> f64 {
|
||||
return self.decode().to_number();
|
||||
}
|
||||
|
||||
fn is_primitive(&self) -> bool {
|
||||
return match self.typeof_() {
|
||||
Undefined => true,
|
||||
Null => true,
|
||||
Bool => true,
|
||||
Number => true,
|
||||
String => true,
|
||||
Array => false,
|
||||
Object => true,
|
||||
Function => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,4 +30,8 @@ impl VsValue for VsString {
|
||||
fn to_number(&self) -> f64 {
|
||||
std::panic!("not implemented");
|
||||
}
|
||||
|
||||
fn is_primitive(&self) -> bool {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,21 @@ pub trait VsValue {
|
||||
fn typeof_(&self) -> VsType;
|
||||
fn to_string(&self) -> String;
|
||||
fn to_number(&self) -> f64;
|
||||
fn is_primitive(&self) -> bool;
|
||||
}
|
||||
|
||||
pub trait ValTrait {
|
||||
fn to_primitive(&self) -> Val;
|
||||
}
|
||||
|
||||
impl ValTrait for Val {
|
||||
fn to_primitive(&self) -> Val {
|
||||
if self.is_primitive() {
|
||||
return self.clone();
|
||||
}
|
||||
|
||||
return VsString::from_string(self.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for dyn VsValue {
|
||||
|
||||
Reference in New Issue
Block a user