Skip to content

Add basic support for String.prototype.char_at() #286

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,4 +189,16 @@ extern {
#[wasm_bindgen(method)]
pub fn includes(this: &Array, value: JsValue, from_index: i32) -> bool;

}

// String
#[wasm_bindgen]
extern {
pub type String;

/// The String object's charAt() method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt
#[wasm_bindgen(method, js_name = charAt)]
pub fn char_at(this: &String, index: i32) -> String;
}
32 changes: 32 additions & 0 deletions tests/all/js_globals/String.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#![allow(non_snake_case)]

use project;

#[test]
fn char_at() {
project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section)]

extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js;

#[wasm_bindgen]
pub fn string_char_at(string: &js::String, index: i32) -> js::String {
string.char_at(index)
}
"#)
.file("test.ts", r#"
import * as assert from "assert";
import * as wasm from "./out";

var anyString = 'Brave new world';
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is taken from the documentation. I haven't added a test case for default index = 0 as I am not sure currently it's possible


export function test() {
assert.equal(wasm.string_char_at(anyString, 0), "B");
assert.equal(wasm.string_char_at(anyString, 999), "");
}
"#)
.test()
}
1 change: 1 addition & 0 deletions tests/all/js_globals/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use super::project;

mod Object;
mod Array;
mod String;

#[test]
#[cfg(feature = "std")]
Expand Down