Skip to content

Commit

Permalink
feat(boa): implements at method for string
Browse files Browse the repository at this point in the history
Closes boa-dev#13
  • Loading branch information
neeldug committed Jun 29, 2021
1 parent 45a5599 commit 16d2c08
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 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,39 @@ 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-additions
/// [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.len();
let relative_index = args
.get(0)
.cloned()
.expect("No index provided")
.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(utf16_val as u32).unwrap()))
} 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 16d2c08

Please sign in to comment.