Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(boa): implements at method for string #1375

Merged
merged 3 commits into from
Jul 24, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
neeldug marked this conversation as resolved.
Show resolved Hide resolved
/// [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();
neeldug marked this conversation as resolved.
Show resolved Hide resolved
let relative_index = args
.get(0)
.cloned()
.expect("No index provided")
neeldug marked this conversation as resolved.
Show resolved Hide resolved
.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()))
neeldug marked this conversation as resolved.
Show resolved Hide resolved
} 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