From 820f9eddfe36813309cf4dc7893bdac2a16bc26e Mon Sep 17 00:00:00 2001 From: daurnimator Date: Fri, 27 Jan 2017 11:46:24 +1100 Subject: [PATCH] luatz/timetable: Fix incorrect math for negative carry operations Closes #10 --- luatz/timetable.lua | 4 ++-- spec/timetable_spec.lua | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/luatz/timetable.lua b/luatz/timetable.lua index e2930d8..0dbf4c8 100644 --- a/luatz/timetable.lua +++ b/luatz/timetable.lua @@ -76,8 +76,8 @@ local function carry ( tens , units , base ) tens = tens + idiv ( units , base ) units = units % base elseif units < 0 then - tens = tens - 1 + idiv ( -units , base ) - units = base - ( -units % base ) + tens = tens + idiv ( units , base ) + units = ( base + units ) % base end return tens , units end diff --git a/spec/timetable_spec.lua b/spec/timetable_spec.lua index ddc05c6..930d36b 100644 --- a/spec/timetable_spec.lua +++ b/spec/timetable_spec.lua @@ -91,6 +91,13 @@ describe ( "Timetable library" , function ( ) assert.same({ 2017,2,15,0,0,0 } , { timetable.normalise(2016,14.5,1,0,0,0) }) end ) + it ( "#normalise handles negative carry (issue #10)", function() + assert.same({ 1970,01,01,00,59,00 }, { timetable.normalise(1970,01,01,01,00,-60) }) + assert.same({ 1970,01,01,00,58,58 }, { timetable.normalise(1970,01,01,01,00,-62) }) + assert.same({ 1969,12,31,23,55,58 }, { timetable.normalise(1970,01,01,01,-63,-62) }) + assert.same({ 2017,02,3,0,0,0 }, { timetable.normalise(2017,02,13,0,-14400,0) }) + end ) + local function round_trip_add(t, field, x) local before = t:clone() t[field]=t[field]+x; -- 2.39.2