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 Number.prototype.toPrecision #962

Merged
merged 9 commits into from
Dec 17, 2020
30 changes: 21 additions & 9 deletions boa/src/builtins/number/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
//! - [ECMAScript reference][spec]
//! - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-number.prototype.toprecision
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision
//! [spec]: https://tc39.es/ecma262/#sec-number-object
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

use super::function::make_builtin_fn;
use crate::{
builtins::BuiltIn,
object::{ConstructorBuilder, ObjectData},
property::Attribute,
value::{AbstractRelation, Value},
value::{AbstractRelation, IntegerOrInfinity, Value},
BoaProfiler, Context, Result,
};
use num_traits::float::FloatCore;
Expand Down Expand Up @@ -318,45 +318,53 @@ impl Number {
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-number.prototype.toexponential
/// [spec]: https://tc39.es/ecma262/#sec-number.prototype.toprecision
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_precision(
this: &Value,
args: &[Value],
context: &mut Context,
) -> Result<Value> {
let precision_arg = args.get(0);
let precision_var = args.get(0).cloned().unwrap_or_default();

// 1 & 6
let mut this_num = Self::this_number_value(this, context)?;
if precision_arg.is_none() || !this_num.is_finite() {
// 2 & 4
if precision_var == Value::undefined() || !this_num.is_finite() {
return Self::to_string(this, &[], context);
}

let precision = match precision_arg.unwrap().to_integer(context)? as i32 {
x @ 1..=100 => x as usize,
// 3
let precision = match precision_var.to_integer_or_infinity(context).unwrap() {
NathanRoyer marked this conversation as resolved.
Show resolved Hide resolved
IntegerOrInfinity::Integer(x) if (1..=100).contains(&x) => x as usize,
_ => {
// 5
return context.throw_range_error(
"precision must be an integer at least 1 and no greater than 100",
)
);
}
};
let precision_i32 = precision as i32;

// 7
let mut prefix = String::new(); // spec: "s"
let mut suffix: String; // spec: "m"
let exponent: i32; // spec: "e"

// 8
if this_num < 0.0 {
prefix.push('-');
this_num = -this_num;
}

let mut is_scientific = false;

// 9
if this_num == 0.0 {
suffix = "0".repeat(precision);
exponent = 0;
// 10
} else {
let mut buffer = ryu_js::Buffer::new();
suffix = buffer.format(this_num).to_string();
Expand Down Expand Up @@ -384,20 +392,24 @@ impl Number {
}
}

// 11
let e_inc = exponent + 1;
if !is_scientific && e_inc != precision_i32 {
// 12
if exponent >= 0 {
suffix.truncate(precision);
if precision > e_inc as usize {
suffix.insert(e_inc as usize, '.');
}
// 13
} else {
prefix.push('0');
prefix.push('.');
prefix.push_str(&"0".repeat(-e_inc as usize));
}
}

// 14
Ok(Value::from(prefix + &suffix))
}

Expand Down
28 changes: 23 additions & 5 deletions boa/src/builtins/number/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,23 +129,29 @@ fn to_locale_string() {
fn to_precision() {
let mut context = Context::new();
let init = r#"
var infinity = (1/0).toPrecision(3);
var default_precision = Number().toPrecision();
var low_precision = Number(123456789).toPrecision(1);
var more_precision = Number(123456789).toPrecision(4);
var exact_precision = Number(123456789).toPrecision(9);
var over_precision = Number(123456789).toPrecision(50);
var neg_precision = Number(-123456789).toPrecision(4);
var explicit_ud_precision = Number().toPrecision(undefined);
var low_precision = (123456789).toPrecision(1);
var more_precision = (123456789).toPrecision(4);
var exact_precision = (123456789).toPrecision(9);
var over_precision = (123456789).toPrecision(50);
var neg_precision = (-123456789).toPrecision(4);
"#;

eprintln!("{}", forward(&mut context, init));
let infinity = forward(&mut context, "infinity");
let default_precision = forward(&mut context, "default_precision");
let explicit_ud_precision = forward(&mut context, "explicit_ud_precision");
let low_precision = forward(&mut context, "low_precision");
let more_precision = forward(&mut context, "more_precision");
let exact_precision = forward(&mut context, "exact_precision");
let over_precision = forward(&mut context, "over_precision");
let neg_precision = forward(&mut context, "neg_precision");

assert_eq!(infinity, String::from("\"Infinity\""));
assert_eq!(default_precision, String::from("\"0\""));
assert_eq!(explicit_ud_precision, String::from("\"0\""));
assert_eq!(low_precision, String::from("\"1e+8\""));
assert_eq!(more_precision, String::from("\"1.235e+8\""));
assert_eq!(exact_precision, String::from("\"123456789\""));
Expand All @@ -154,6 +160,18 @@ fn to_precision() {
over_precision,
String::from("\"123456789.00000000000000000000000000000000000000000\"")
);

let expected = "Uncaught \"RangeError\": \"precision must be an integer at least 1 and no greater than 100\"";

let range_error_1 = r#"(1).toPrecision(101);"#;
let range_error_2 = r#"(1).toPrecision(0);"#;
let range_error_3 = r#"(1).toPrecision(-2000);"#;
let range_error_4 = r#"(1).toPrecision('%');"#;

assert_eq!(forward(&mut context, range_error_1), expected);
assert_eq!(forward(&mut context, range_error_2), expected);
assert_eq!(forward(&mut context, range_error_3), expected);
assert_eq!(forward(&mut context, range_error_4), expected);
}

#[test]
Expand Down