2
0
Эх сурвалжийг харах

Applied fix for #144 to typed arrays.

Dmitry Panov 5 жил өмнө
parent
commit
af442b8aa0

+ 16 - 2
builtin_typedarrays.go

@@ -1,6 +1,7 @@
 package goja
 package goja
 
 
 import (
 import (
+	"math"
 	"sort"
 	"sort"
 	"strings"
 	"strings"
 	"unsafe"
 	"unsafe"
@@ -28,9 +29,22 @@ func (ctx *typedArraySortCtx) Less(i, j int) bool {
 		res := ctx.compare(FunctionCall{
 		res := ctx.compare(FunctionCall{
 			This:      _undefined,
 			This:      _undefined,
 			Arguments: []Value{x, y},
 			Arguments: []Value{x, y},
-		}).ToInteger()
+		}).ToNumber()
 		ctx.needValidate = true
 		ctx.needValidate = true
-		return res < 0
+		if i, ok := res.(valueInt); ok {
+			return i < 0
+		}
+		f := res.ToFloat()
+		if f < 0 {
+			return true
+		}
+		if f > 0 {
+			return false
+		}
+		if math.Signbit(f) {
+			return true
+		}
+		return false
 	}
 	}
 
 
 	return ctx.ta.typedArray.less(offset+i, offset+j)
 	return ctx.ta.typedArray.less(offset+i, offset+j)

+ 32 - 0
builtin_typedarrays_test.go

@@ -264,3 +264,35 @@ func TestTypedArraySliceDifType(t *testing.T) {
 	`
 	`
 	testScript1(SCRIPT, _undefined, t)
 	testScript1(SCRIPT, _undefined, t)
 }
 }
+
+func TestTypedArraySortComparatorReturnValueFloats(t *testing.T) {
+	const SCRIPT = `
+	var a = Float64Array.of(
+		5.97,
+		9.91,
+		4.13,
+		9.28,
+		3.29
+	);
+	a.sort( function(a, b) { return a - b; } );
+	for (var i = 1; i < a.length; i++) {
+		if (a[i] < a[i-1]) {
+			throw new Error("Array is not sorted: " + a);
+		}
+	}
+	`
+	testScript1(SCRIPT, _undefined, t)
+}
+
+func TestTypedArraySortComparatorReturnValueNegZero(t *testing.T) {
+	const SCRIPT = `
+	var a = new Uint8Array([2, 1]);
+	a.sort( function(a, b) { return a > b ? 0 : -0; } );
+	for (var i = 1; i < a.length; i++) {
+		if (a[i] < a[i-1]) {
+			throw new Error("Array is not sorted: " + a);
+		}
+	}
+	`
+	testScript1(SCRIPT, _undefined, t)
+}