Browse Source

Fixed IsNaN()

Dmitry Panov 6 years ago
parent
commit
bf663de44c
2 changed files with 56 additions and 0 deletions
  1. 26 0
      runtime.go
  2. 30 0
      runtime_test.go

+ 26 - 0
runtime.go

@@ -1476,6 +1476,17 @@ func IsNull(v Value) bool {
 	return v == _null
 }
 
+// IsNaN returns true if the supplied value is NaN.
+func IsNaN(v Value) bool {
+	f, ok := v.assertFloat()
+	return ok && math.IsNaN(f)
+}
+
+// IsInfinity returns true if the supplied is (+/-)Infinity
+func IsInfinity(v Value) bool {
+	return v == _positiveInf || v == _negativeInf
+}
+
 // Undefined returns JS undefined value. Note if global 'undefined' property is changed this still returns the original value.
 func Undefined() Value {
 	return _undefined
@@ -1486,6 +1497,21 @@ func Null() Value {
 	return _null
 }
 
+// NaN returns a JS NaN value.
+func NaN() Value {
+	return _NaN
+}
+
+// PositiveInf returns a JS +Inf value.
+func PositiveInf() Value {
+	return _positiveInf
+}
+
+// NegativeInf returns a JS -Inf value.
+func NegativeInf() Value {
+	return _negativeInf
+}
+
 func tryFunc(f func()) (err error) {
 	defer func() {
 		if x := recover(); x != nil {

+ 30 - 0
runtime_test.go

@@ -1228,6 +1228,36 @@ func TestRunLoopPreempt(t *testing.T) {
 	}
 }
 
+func TestNaN(t *testing.T) {
+	if !IsNaN(_NaN) {
+		t.Fatal("IsNaN() doesn't detect NaN")
+	}
+	if IsNaN(Undefined()) {
+		t.Fatal("IsNaN() says undefined is a NaN")
+	}
+	if !IsNaN(NaN()) {
+		t.Fatal("NaN() doesn't return NaN")
+	}
+}
+
+func TestInf(t *testing.T) {
+	if !IsInfinity(_positiveInf) {
+		t.Fatal("IsInfinity() doesn't detect +Inf")
+	}
+	if !IsInfinity(_negativeInf) {
+		t.Fatal("IsInfinity() doesn't detect -Inf")
+	}
+	if IsInfinity(Undefined()) {
+		t.Fatal("IsInfinity() says undefined is a Infinity")
+	}
+	if !IsInfinity(PositiveInf()) {
+		t.Fatal("PositiveInfinity() doesn't return Inf")
+	}
+	if !IsInfinity(NegativeInf()) {
+		t.Fatal("NegativeInfinity() doesn't return Inf")
+	}
+}
+
 /*
 func TestArrayConcatSparse(t *testing.T) {
 function foo(a,b,c)