From bf011a016070e35cfe5a31e4426ee82e01efbbde Mon Sep 17 00:00:00 2001 From: Bob Thomas Date: Wed, 17 Feb 2021 10:30:55 -0500 Subject: [PATCH] Fix ordering operators for non-numbers According to the spec, ordering operators are only valid for numbers, but all types were being compared according to JavaScript rules instead. Fix the interpretation of ordering operators to conform to the spec and return null for any non-numbers. Fixes #42 Fixes #51 --- jmespath.js | 13 +++++++++---- test/compliance/boolean.json | 28 +++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/jmespath.js b/jmespath.js index 0a36691..bddb0a6 100644 --- a/jmespath.js +++ b/jmespath.js @@ -67,6 +67,11 @@ return false; } + // Ordering operators are only valid for numbers + function compareable(first, second) { + return (typeof first === 'number' && typeof second === 'number'); + } + function isFalse(obj) { // From the spec: // A false value corresponds to the following values: @@ -985,16 +990,16 @@ result = !strictDeepEqual(first, second); break; case TOK_GT: - result = first > second; + result = compareable(first, second) ? first > second : null; break; case TOK_GTE: - result = first >= second; + result = compareable(first, second) ? first >= second : null; break; case TOK_LT: - result = first < second; + result = compareable(first, second) ? first < second : null; break; case TOK_LTE: - result = first <= second; + result = compareable(first, second) ? first <= second : null; break; default: throw new Error("Unknown comparator: " + node.name); diff --git a/test/compliance/boolean.json b/test/compliance/boolean.json index e3fa196..1beaacb 100644 --- a/test/compliance/boolean.json +++ b/test/compliance/boolean.json @@ -76,7 +76,9 @@ "False": false, "Number": 5, "EmptyList": [], - "Zero": 0 + "Zero": 0, + "String": "foo", + "Null": null }, "cases": [ { @@ -198,6 +200,30 @@ { "expression": "!!Zero", "result": true + }, + { + "expression": "String < Number", + "result": null + }, + { + "expression": "Number < String", + "result": null + }, + { + "expression": "Null < Number", + "result": null + }, + { + "expression": "Number < Null", + "result": null + }, + { + "expression": "Null < String", + "result": null + }, + { + "expression": "String < Null", + "result": null } ] },