From 4f294224f079cfae9d1388edbc07f1f62601f815 Mon Sep 17 00:00:00 2001 From: Danielle Pham Date: Sun, 19 Aug 2018 15:09:45 -0400 Subject: [PATCH] Add bindings for String.prototype.split --- crates/js-sys/src/lib.rs | 11 ++++++++++ crates/js-sys/tests/wasm/JsString.rs | 33 ++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/crates/js-sys/src/lib.rs b/crates/js-sys/src/lib.rs index 6c491346..6f36d8f8 100644 --- a/crates/js-sys/src/lib.rs +++ b/crates/js-sys/src/lib.rs @@ -3103,6 +3103,17 @@ extern "C" { #[wasm_bindgen(method, js_class = "String")] pub fn slice(this: &JsString, start: u32, end: u32) -> JsString; + /// The split() method splits a String object into an array of strings by separating the string + /// into substrings, using a specified separator string to determine where to make each split. + /// + /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split + #[wasm_bindgen(method, js_class = "String")] + pub fn split(this: &JsString, separator: &str) -> Array; + + /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split + #[wasm_bindgen(method, js_class = "String", js_name = split)] + pub fn split_limit(this: &JsString, separator: &str, limit: u32) -> Array; + /// The `startsWith()` method determines whether a string begins with the /// characters of a specified string, returning true or false as /// appropriate. diff --git a/crates/js-sys/tests/wasm/JsString.rs b/crates/js-sys/tests/wasm/JsString.rs index 898ee767..5458e3e7 100644 --- a/crates/js-sys/tests/wasm/JsString.rs +++ b/crates/js-sys/tests/wasm/JsString.rs @@ -321,6 +321,39 @@ fn slice() { assert_eq!(characters.slice(1, 3), "cx"); } +#[wasm_bindgen_test] +fn split() { + let js = JsString::from("Oh brave new world"); + let result = js.split(" "); + + let mut v = Vec::with_capacity(result.length() as usize); + result.for_each(&mut |x, _, _| v.push(x)); + + assert_eq!(v[0], "Oh"); + assert_eq!(v[1], "brave"); + assert_eq!(v[2], "new"); + assert_eq!(v[3], "world"); + + let js = JsString::from("Oct,Nov,Dec"); + let result = js.split(","); + + let mut v = Vec::with_capacity(result.length() as usize); + result.for_each(&mut |x, _, _| v.push(x)); + + assert_eq!(v[0], "Oct"); + assert_eq!(v[1], "Nov"); + assert_eq!(v[2], "Dec"); + + let result = js.split_limit(",", 2); + + let mut v = Vec::with_capacity(result.length() as usize); + result.for_each(&mut |x, _, _| v.push(x)); + + assert_eq!(result.length(), 2); + assert_eq!(v[0], "Oct"); + assert_eq!(v[1], "Nov"); +} + #[wasm_bindgen_test] fn starts_with() { let js = JsString::from("To be, or not to be, that is the question.");