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

Implement String.fromCharCode #1619

Merged
merged 1 commit into from
Oct 4, 2021
Merged
Changes from all commits
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
30 changes: 30 additions & 0 deletions boa/src/builtins/string/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ impl BuiltIn for String {
.name(Self::NAME)
.length(Self::LENGTH)
.property("length", 0, attribute)
.static_method(Self::from_char_code, "fromCharCode", 1)
.method(Self::char_at, "charAt", 1)
.method(Self::char_code_at, "charCodeAt", 1)
.method(Self::code_point_at, "codePointAt", 1)
Expand Down Expand Up @@ -240,6 +241,35 @@ impl String {
Err(context.construct_type_error("'this' is not a string"))
}

/// `String.fromCharCode(...codePoints)`
///
/// Construct a `String` from one or more code points (as numbers).
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/multipage/text-processing.html#sec-string.fromcharcode
pub(crate) fn from_char_code(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let length be the number of elements in codeUnits.
// 2. Let elements be a new empty List.
let mut elements = Vec::new();
// 3. For each element next of codeUnits, do
for next in args {
// 3a. Let nextCU be ℝ(? ToUint16(next)).
// 3b. Append nextCU to the end of elements.
elements.push(next.to_u32(context)? as u16);
}
Comment on lines +258 to +264
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just noting that, when #1552 gets merged, this should be simplified further to:

args.iter()
    .map(|val| val.to_u16(context))
    .collect::<JsResult<Vec<_>>>()?;


// 4. Return the String value whose code units are the elements in the List elements.
// If codeUnits is empty, the empty String is returned.

let s = std::string::String::from_utf16_lossy(elements.as_slice());
Ok(JsValue::String(JsString::new(s)))
}

/// Get the string value to a primitive string
#[allow(clippy::wrong_self_convention)]
#[inline]
Expand Down