Skip to content
Open
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions Sources/JSON/JSON.swift
Original file line number Diff line number Diff line change
Expand Up @@ -258,15 +258,27 @@ public enum JSON: Equatable {
public static func / (lhs: JSON, rhs: JSON) -> JSON {
switch (lhs, rhs) {
case let (.Double(x), .Double(y)):
guard y != 0 else {
return JSON.Null
}
return .Double(x / y)
case let (.Int(x), .Int(y)):
guard y != 0 else {
return JSON.Null
}
if x % y == 0 {
return .Int(x / y)
}
return .Double(Swift.Double(x) / Swift.Double(y))
case let (.Double(x), .Int(y)):
guard y != 0 else {
return JSON.Null
}
return .Double(x / Swift.Double(y))
case let (.Int(x), .Double(y)):
guard y != 0 else {
return JSON.Null
}
return .Double(Swift.Double(x) / y)
default:
return JSON.Null
Expand All @@ -276,12 +288,24 @@ public enum JSON: Equatable {
public static func % (lhs: JSON, rhs: JSON) -> JSON {
switch (lhs, rhs) {
case let (.Double(x), .Double(y)):
guard y != 0 else {
return JSON.Null
}
return .Double(x.truncatingRemainder(dividingBy: y))
case let (.Int(x), .Int(y)):
guard y != 0 else {
return JSON.Null
}
return .Int(x % y)
case let (.Double(x), .Int(y)):
guard y != 0 else {
return JSON.Null
}
return .Double(x.truncatingRemainder(dividingBy: Swift.Double(y)))
case let (.Int(x), .Double(y)):
guard y != 0 else {
return JSON.Null
}
return .Double(Swift.Double(x).truncatingRemainder(dividingBy: y))
default:
return JSON.Null
Expand Down
28 changes: 28 additions & 0 deletions Tests/jsonlogicTests/ArithmeticTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,20 @@ class Arithmetic: XCTestCase {
XCTAssertEqual(1, try applyRule(rule, to: nil))
}

func testDivisionByZero() {
let rule =
"""
{ "/" : [4, 0]}
"""
XCTAssertThrowsError(try applyRule(rule, to: nil) as Double) { error in
XCTAssertEqual(error as! JSONLogicError, JSONLogicError.canNotConvertResultToType(Double.self))
}

XCTAssertThrowsError(try applyRule(rule, to: nil) as Int) { error in
XCTAssertEqual(error as! JSONLogicError, JSONLogicError.canNotConvertResultToType(Int.self))
}
}

func testModulo() {
var rule =
"""
Expand All @@ -154,6 +168,20 @@ class Arithmetic: XCTestCase {
XCTAssertEqual(1, try applyRule(rule, to: nil))
}

func testModuloByZero() {
let rule =
"""
{ "%" : [4, 0]}
"""
XCTAssertThrowsError(try applyRule(rule, to: nil) as Double) { error in
XCTAssertEqual(error as! JSONLogicError, JSONLogicError.canNotConvertResultToType(Double.self))
}

XCTAssertThrowsError(try applyRule(rule, to: nil) as Int) { error in
XCTAssertEqual(error as! JSONLogicError, JSONLogicError.canNotConvertResultToType(Int.self))
}
}

func testUnaryMinus() {
var rule =
"""
Expand Down