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

Sprite.prototype.toNumber(value, true) - strict cast to number #203

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
27 changes: 22 additions & 5 deletions src/Sprite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,18 +394,35 @@ abstract class SpriteBase {
return this._project.loudness;
}

public toNumber(value: unknown): number {
// Strict mode uses essentially the same logic as compare() uses when treating
// the sides as numbers. It exists to handle NaN or NaN-casting values inside
// a normal "===" comparison, preferring "===" when possible, to writing all
// numeric comparisons with this.compare().
public toNumber(value: unknown, strict: boolean = false): number {
if (Number.isNaN(value)) {
return strict ? NaN : 0;
}

if (typeof value === "number") {
if (isNaN(value)) {
return 0;
}
return value;
}

const n = Number(value);

if (Number.isNaN(n)) {
return 0;
return strict ? NaN : 0;
}

if (strict && n === 0) {
if (value === null) {
return null;
}

if (typeof value === "string" && value.trim().length === 0) {
return NaN;
}
}

return n;
}

Expand Down