Skip to content

Commit

Permalink
support indexOf/lastIndexOf start/end indices
Browse files Browse the repository at this point in the history
  • Loading branch information
y21 committed Jul 29, 2024
1 parent cd8cff2 commit fd17acd
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions crates/dash_vm/src/js_std/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,19 +147,32 @@ pub fn includes(cx: CallContext) -> Result<Value, Value> {
pub fn index_of(cx: CallContext) -> Result<Value, Value> {
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))
}

pub fn last_index_of(cx: CallContext) -> Result<Value, Value> {
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);
Expand Down

0 comments on commit fd17acd

Please sign in to comment.