From fd17acd379bfe7072e069a043d177529ace57544 Mon Sep 17 00:00:00 2001 From: y21 <30553356+y21@users.noreply.github.com> Date: Tue, 30 Jul 2024 01:45:23 +0200 Subject: [PATCH] support indexOf/lastIndexOf start/end indices --- crates/dash_vm/src/js_std/string.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/dash_vm/src/js_std/string.rs b/crates/dash_vm/src/js_std/string.rs index 2f4a38ca..49cd3dfe 100644 --- a/crates/dash_vm/src/js_std/string.rs +++ b/crates/dash_vm/src/js_std/string.rs @@ -147,10 +147,16 @@ pub fn includes(cx: CallContext) -> Result { pub fn index_of(cx: CallContext) -> Result { let this = cx.this.to_js_string(cx.scope)?; let other = cx.args.first().unwrap_or_undefined().to_js_string(cx.scope)?; + let start_index = match cx.args.get(1) { + Some(n) => n.to_length_u(cx.scope)?, + None => 0, + }; + let this = this.res(cx.scope); let pos = this - .res(cx.scope) + .get(start_index..) + .unwrap_or("") .find(other.res(cx.scope)) - .map(|i| i as f64) + .map(|i| (start_index + i) as f64) .unwrap_or(-1.0); Ok(Value::number(pos)) } @@ -158,8 +164,15 @@ pub fn index_of(cx: CallContext) -> Result { pub fn last_index_of(cx: CallContext) -> Result { let this = cx.this.to_js_string(cx.scope)?; let other = cx.args.first().unwrap_or_undefined().to_js_string(cx.scope)?; + let end_index = match cx.args.get(1) { + Some(n) => n.to_length_u(cx.scope)? + 1, + None => this.res(cx.scope).len(), + }; + + let this = this.res(cx.scope); let pos = this - .res(cx.scope) + .get(..end_index) + .unwrap_or(this) .rfind(other.res(cx.scope)) .map(|i| i as f64) .unwrap_or(-1.0);