mirror of
https://github.com/scratchfoundation/scratch-vm.git
synced 2025-03-14 01:09:51 -04:00
Merge pull request #1709 from mzgoddard/cast-to-number
Shortcut Cast.toNumber if given a number
This commit is contained in:
commit
692b71a737
1 changed files with 20 additions and 1 deletions
|
@ -1,5 +1,13 @@
|
|||
const Color = require('../util/color');
|
||||
|
||||
/**
|
||||
* Store and possibly polyfill Number.isNaN. Number.isNaN can save time over
|
||||
* self.isNaN by not coercing its input. We need to polyfill it to support
|
||||
* Internet Explorer.
|
||||
* @const
|
||||
*/
|
||||
const _NumberIsNaN = Number.isNaN || isNaN;
|
||||
|
||||
/**
|
||||
* @fileoverview
|
||||
* Utilities for casting and comparing Scratch data-types.
|
||||
|
@ -20,8 +28,19 @@ class Cast {
|
|||
* @return {number} The Scratch-casted number value.
|
||||
*/
|
||||
static toNumber (value) {
|
||||
// If value is already a number we don't need to coerce it with
|
||||
// Number().
|
||||
if (typeof value === 'number') {
|
||||
// Scratch treats NaN as 0, when needed as a number.
|
||||
// E.g., 0 + NaN -> 0.
|
||||
if (_NumberIsNaN(value)) {
|
||||
return 0;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
const n = Number(value);
|
||||
if (isNaN(n)) {
|
||||
if (_NumberIsNaN(n)) {
|
||||
// Scratch treats NaN as 0, when needed as a number.
|
||||
// E.g., 0 + NaN -> 0.
|
||||
return 0;
|
||||
|
|
Loading…
Reference in a new issue