Add is_truthy, is_falsy

This commit is contained in:
Thomas
2019-07-02 18:44:06 +02:00
parent bf631eda1b
commit e61f691e0b
4 changed files with 59 additions and 0 deletions

View File

@ -85,6 +85,12 @@ intrinsics! {
#[symbol = "__wbindgen_is_string"]
#[signature = fn(ref_anyref()) -> Boolean]
IsString,
#[symbol = "__wbindgen_is_truthy"]
#[signature = fn(ref_anyref()) -> Boolean]
IsTruthy,
#[symbol = "__wbindgen_is_falsy"]
#[signature = fn(ref_anyref()) -> Boolean]
IsFalsy,
#[symbol = "__wbindgen_object_clone_ref"]
#[signature = fn(ref_anyref()) -> Anyref]
ObjectCloneRef,

View File

@ -2299,6 +2299,16 @@ impl<'a> Context<'a> {
format!("typeof({}) === 'string'", args[0])
}
Intrinsic::IsTruthy => {
assert_eq!(args.len(), 1);
format!("!!{}", args[0])
}
Intrinsic::IsFalsy => {
assert_eq!(args.len(), 1);
format!("!{}", args[0])
}
Intrinsic::ObjectCloneRef => {
assert_eq!(args.len(), 1);
args[0].clone()

View File

@ -332,6 +332,22 @@ impl JsValue {
unsafe { __wbindgen_is_function(self.idx) == 1 }
}
/// Tests whether the value is ["truthy"].
///
/// ["truthy"]: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
#[inline]
pub fn is_truthy(&self) -> bool {
unsafe { __wbindgen_is_truthy(self.idx) == 1 }
}
/// Tests whether the value is ["falsy"].
///
/// ["falsy"]: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
#[inline]
pub fn is_falsy(&self) -> bool {
unsafe { __wbindgen_is_falsy(self.idx) == 1 }
}
/// Get a string representation of the JavaScript object for debugging
#[cfg(feature = "std")]
fn as_debug_string(&self) -> String {
@ -502,6 +518,8 @@ externs! {
fn __wbindgen_is_object(idx: u32) -> u32;
fn __wbindgen_is_function(idx: u32) -> u32;
fn __wbindgen_is_string(idx: u32) -> u32;
fn __wbindgen_is_truthy(idx: u32) -> u32;
fn __wbindgen_is_falsy(idx: u32) -> u32;
fn __wbindgen_number_get(idx: u32, invalid: *mut u8) -> f64;
fn __wbindgen_boolean_get(idx: u32) -> u32;

View File

@ -0,0 +1,25 @@
#[wasm_bindgen_test]
fn test_is_truthy() {
assert_eq!(JsValue::from(0).is_truthy(), false);
assert_eq!(JsValue::from("".to_string()).is_truthy(), false);
assert_eq!(JsValue::from(false).is_truthy(), false);
assert_eq!(JsValue::NULL.is_truthy(), false);
assert_eq!(JsValue::UNDEFINED.is_truthy(), false);
assert_eq!(JsValue::from(10).is_truthy(), true);
assert_eq!(JsValue::from("null".to_string()).is_truthy(), true);
assert_eq!(JsValue::from(true).is_truthy(), true);
}
#[wasm_bindgen_test]
fn test_is_falsy() {
assert_eq!(JsValue::from(0).is_falsy(), true);
assert_eq!(JsValue::from("".to_string()).is_falsy(), true);
assert_eq!(JsValue::from(false).is_falsy(), true);
assert_eq!(JsValue::NULL.is_falsy(), true);
assert_eq!(JsValue::UNDEFINED.is_falsy(), true);
assert_eq!(JsValue::from(10).is_falsy(), false);
assert_eq!(JsValue::from("null".to_string()).is_falsy(), false);
assert_eq!(JsValue::from(true).is_falsy(), false);
}