Skip to content

Commit

Permalink
feat(boa): implements at method for string (#1375)
Browse files Browse the repository at this point in the history
* feat(boa): implements `at` method for string

Closes #13

* cleanup

* fix len
  • Loading branch information
neeldug authored Jul 24, 2021
1 parent a4a76fe commit 7c046ea
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions boa/src/builtins/string/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ impl BuiltIn for String {
.method(Self::replace, "replace", 2)
.method(Self::iterator, (symbol_iterator, "[Symbol.iterator]"), 0)
.method(Self::search, "search", 1)
.method(Self::at, "at", 1)
.build();

(Self::NAME, string_object.into(), Self::attribute())
Expand Down Expand Up @@ -266,6 +267,41 @@ impl String {
}
}

/// `String.prototype.at ( index )`
///
/// This String object's at() method returns a String consisting of the single UTF-16 code unit located at the specified position.
/// Returns undefined if the given index cannot be found.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/proposal-relative-indexing-method/#sec-string.prototype.at
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/at
pub(crate) fn at(this: &Value, args: &[Value], context: &mut Context) -> Result<Value> {
let this = this.require_object_coercible(context)?;
let s = this.to_string(context)?;
let len = s.encode_utf16().count();
let relative_index = args
.get(0)
.cloned()
.unwrap_or_default()
.to_integer(context)?;
let k = if relative_index < 0 as f64 {
len - (-relative_index as usize)
} else {
relative_index as usize
};

if let Some(utf16_val) = s.encode_utf16().nth(k) {
Ok(Value::from(
from_u32(u32::from(utf16_val)).expect("invalid utf-16 character"),
))
} else {
Ok(Value::undefined())
}
}

/// `String.prototype.codePointAt( index )`
///
/// The `codePointAt()` method returns an integer between `0` to `1114111` (`0x10FFFF`) representing the UTF-16 code unit at the given index.
Expand Down

0 comments on commit 7c046ea

Please sign in to comment.