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
127 changes: 115 additions & 12 deletions boa/src/builtins/number/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
//! - [ECMAScript reference][spec]
//! - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-number-object
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
//! [spec]: https://tc39.es/ecma262/#sec-number.prototype.toprecision
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision

use super::function::make_builtin_fn;
use crate::{
Expand Down Expand Up @@ -269,6 +269,47 @@ impl Number {
Ok(Value::from(this_str_num))
}

fn flt_str_to_exp(flt: &str) -> i32 {
let mut nz_encountered = false;
let mut dot_encountered = false;
for (i, c) in flt.chars().enumerate() {
if c == '.' {
if nz_encountered {
return (i as i32) - 1;
}
dot_encountered = true;
} else if c != '0' {
if dot_encountered {
return 1 - (i as i32);
}
nz_encountered = true;
}
}
(flt.len() as i32) - 1
}

fn round_to_precision(digits: &mut String, precision: usize) {
if digits.len() > precision {
let to_round = digits.split_off(precision);
let mut digit = digits.pop().unwrap() as u8;

for c in to_round.chars() {
match c {
c if c < '4' => break,
c if c > '4' => {
digit += 1;
break;
}
_ => {}
}
}

digits.push(digit as char);
} else {
digits.push_str(&"0".repeat(precision - digits.len()));
}
}

/// `Number.prototype.toPrecision( [precision] )`
///
/// The `toPrecision()` method returns a string representing the Number object to the specified precision.
Expand All @@ -285,17 +326,79 @@ impl Number {
args: &[Value],
context: &mut Context,
) -> Result<Value> {
let this_num = Self::this_number_value(this, context)?;
let _num_str_len = format!("{}", this_num).len();
let _precision = match args.get(0) {
Some(n) => match n.to_integer(context)? as i32 {
x if x > 0 => n.to_integer(context)? as usize,
_ => 0,
},
None => 0,
let precision_arg = args.get(0);

let mut this_num = Self::this_number_value(this, context)?;
if precision_arg.is_none() || !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,
_ => {
return context.throw_range_error(
"precision must be an integer at least 1 and no greater than 100",
)
}
};
// TODO: Implement toPrecision
unimplemented!("TODO: Implement toPrecision");
let precision_i32 = precision as i32;

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

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

let mut is_scientific = false;

if this_num == 0.0 {
suffix = "0".repeat(precision);
exponent = 0;
} else {
let mut buffer = ryu_js::Buffer::new();
suffix = buffer.format(this_num).to_string();

exponent = Self::flt_str_to_exp(&suffix);
if exponent < 0 {
suffix = suffix.split_off((1 - exponent) as usize);
} else if let Some(n) = suffix.find('.') {
suffix.remove(n);
}
Self::round_to_precision(&mut suffix, precision);

let great_exp = exponent >= precision_i32;
if exponent < -6 || great_exp {
is_scientific = true;
suffix.truncate(precision);
if precision > 1 {
suffix.insert(1, '.');
}
suffix.push('e');
if great_exp {
suffix.push('+');
}
suffix.push_str(&exponent.to_string());
}
NathanRoyer marked this conversation as resolved.
Show resolved Hide resolved
}

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

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

// https://golang.org/src/math/nextafter.go
Expand Down
13 changes: 6 additions & 7 deletions boa/src/builtins/number/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,6 @@ fn to_locale_string() {
}

#[test]
#[ignore]
fn to_precision() {
let mut context = Context::new();
let init = r#"
Expand All @@ -146,15 +145,15 @@ fn to_precision() {
let over_precision = forward(&mut context, "over_precision");
let neg_precision = forward(&mut context, "neg_precision");

assert_eq!(default_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"));
assert_eq!(default_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\""));
assert_eq!(neg_precision, String::from("\"-1.235e+8\""));
assert_eq!(
over_precision,
String::from("123456789.00000000000000000000000000000000000000000")
String::from("\"123456789.00000000000000000000000000000000000000000\"")
);
assert_eq!(neg_precision, String::from("-1.235e+8"));
}

#[test]
Expand Down