coder-mike / microvium

A compact, embeddable scripting engine for applications and microcontrollers for executing programs written in a subset of the JavaScript language.
MIT License
569 stars 25 forks source link

Casting string to integer/number #62

Closed boogie closed 1 year ago

boogie commented 1 year ago

Probably it is trivial, but I've found no documentation about it. If I have a string value, how can I convert it to number?

let str = '42';
let num1 = +str;
let num2 = Number(str);
let num3 = 0 + str;
let num4 = 1 * str;

I would say these are bugs, in normal JavaScript adding a string to a number should end up in a number. These seems to be not working, and I think there's no parseInt method as well (however it's possible to implement).

coder-mike commented 1 year ago

Hi. Yes, you're right. The code path for coercing a string to a number is currently not implemented. You're the first person to ask for this functionality. I'll leave this ticket open to track progress on it.

In the meantime, as you say, you can implement a method like parseInt in C and import it.

coder-mike commented 1 year ago

Ok, Microvium now supports the unary + operator for converting strings to 32-bit integers (but not general floating point numbers). This is in main in the repository but has not yet been released to npm.

Note:

Does your use case require parsing of floats as well at this time? Otherwise I'll wait for someone else to require that before implementing it.

And another question: are you using microvium off npm or are you using it from source from GitHub?

P.S. these are the test cases and show what cases are covered:

  assert(Number.isNaN(+"x"));
  assert(Number.isNaN(+"length"));
  assert(Number.isNaN(+"__proto__"));
  assert(Number.isNaN(+"1a"));
  assert(Number.isNaN(+"1.1.1"));
  assert(Number.isNaN(+"123456789123456789.1.1"));
  assert(Number.isNaN(+"123\0"));

  // Empty string
  assertEqual(+"", 0);

  // Whitespace
  assertEqual(+"  ", 0);

  // Small integers
  assertEqual(+"123", 123);
  assertEqual(+"-123", -123);

  // Leading and trailing whitespace
  assertEqual(+"  123   ", 123);
  assertEqual(+"  -123   ", -123);

  // Int32
  assertEqual(+"12345678", 12345678);
  assertEqual(+"-12345678", -12345678);

  // Multiply
  assertEqual(1 * "123", 123);
boogie commented 1 year ago

Thanks for adding the support. I don't need floats now. I'm using both npm and source code. I've a JS => bytecode server with npm, and just added microvium C sources to my firmware code by downloading the source.