Skip to content

Commit 5f2f30d

Browse files
data-pupalexcrichton
authored andcommitted
String - lastIndexOf (#490)
1 parent 9d27b44 commit 5f2f30d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/js.rs

+8
Original file line numberDiff line numberDiff line change
@@ -1889,6 +1889,14 @@ extern "C" {
18891889
#[wasm_bindgen(method, js_class = "String", js_name = indexOf)]
18901890
pub fn index_of(this: &JsString, search_value: &JsString, from_index: i32) -> i32;
18911891

1892+
/// The `lastIndexOf()` method returns the index within the calling String
1893+
/// object of the last occurrence of the specified value, searching
1894+
/// backwards from fromIndex. Returns -1 if the value is not found.
1895+
///
1896+
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
1897+
#[wasm_bindgen(method, js_class = "String", js_name = lastIndexOf)]
1898+
pub fn last_index_of(this: &JsString, search_value: &JsString, from_index: i32) -> i32;
1899+
18921900
/// The `slice()` method extracts a section of a string and returns it as a
18931901
/// new string, without modifying the original string.
18941902
///

tests/all/js_globals/JsString.rs

+39
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,45 @@ fn index_of() {
261261
.test()
262262
}
263263

264+
#[test]
265+
fn last_index_of() {
266+
project()
267+
.file("src/lib.rs", r#"
268+
#![feature(use_extern_macros, wasm_custom_section)]
269+
270+
extern crate wasm_bindgen;
271+
use wasm_bindgen::prelude::*;
272+
use wasm_bindgen::js;
273+
274+
#[wasm_bindgen]
275+
pub fn string_last_index_of(this: &js::JsString, search_value: &js::JsString, from_index: i32) -> i32 {
276+
this.last_index_of(search_value, from_index)
277+
}
278+
"#)
279+
.file("test.js", r#"
280+
import * as assert from "assert";
281+
import * as wasm from "./out";
282+
283+
export function test() {
284+
let str = "canal";
285+
let len = str.length;
286+
287+
// TODO: remove second parameter once we have optional parameters
288+
assert.equal(wasm.string_last_index_of(str, 'a', len), 3);
289+
assert.equal(wasm.string_last_index_of(str, 'a', 2), 1);
290+
assert.equal(wasm.string_last_index_of(str, 'a', 0), -1);
291+
// TODO: remove second parameter once we have optional parameters
292+
assert.equal(wasm.string_last_index_of(str, 'x', len), -1);
293+
assert.equal(wasm.string_last_index_of(str, 'c', -5), 0);
294+
assert.equal(wasm.string_last_index_of(str, 'c', 0), 0);
295+
// TODO: remove second parameter once we have optional parameters
296+
assert.equal(wasm.string_last_index_of(str, '', len), 5);
297+
assert.equal(wasm.string_last_index_of(str, '', 2), 2);
298+
}
299+
"#)
300+
.test()
301+
}
302+
264303
#[test]
265304
fn slice() {
266305
project()

0 commit comments

Comments
 (0)