From fff2f5da599cc1ab85006cc729cf0f68c8373103 Mon Sep 17 00:00:00 2001 From: Ozzie Gooen Date: Sun, 22 May 2022 21:57:13 -0400 Subject: [PATCH] More sophisticated makeFromYear function, that accepts floats --- .../ReducerInterface_DateTime.res | 2 +- .../squiggle-lang/src/rescript/Utility/E.res | 30 +++++++++++-------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/packages/squiggle-lang/src/rescript/ReducerInterface/ReducerInterface_DateTime.res b/packages/squiggle-lang/src/rescript/ReducerInterface/ReducerInterface_DateTime.res index 4f474312..97d35c49 100644 --- a/packages/squiggle-lang/src/rescript/ReducerInterface/ReducerInterface_DateTime.res +++ b/packages/squiggle-lang/src/rescript/ReducerInterface/ReducerInterface_DateTime.res @@ -7,7 +7,7 @@ let dateDispatch = (call: ExpressionValue.functionCall, env: DistributionOperati switch call { | ("toString", [EvDate(t)]) => EvString(E.Date.toString(t))->Ok->Some | ("makeDateFromYear", [EvNumber(year)]) => - switch E.Date.makeWithYear(Belt.Float.toInt(year)) { + switch E.Date.makeFromYear(year) { | Ok(t) => EvDate(t)->Ok->Some | Error(e) => RETodo(e)->Error->Some } diff --git a/packages/squiggle-lang/src/rescript/Utility/E.res b/packages/squiggle-lang/src/rescript/Utility/E.res index 088867c9..38967979 100644 --- a/packages/squiggle-lang/src/rescript/Utility/E.res +++ b/packages/squiggle-lang/src/rescript/Utility/E.res @@ -873,18 +873,6 @@ module Date = { type t = Js.Date.t let toFloat = Js.Date.getTime let getFullYear = Js.Date.getFullYear - - //The Js.Date.makeWithYM function accepts a float, but only treats it as a whole number. - //Our version takes an integer to make this distinction clearer. - let makeWithYear = (y: int): result => { - if y < 100 { - Error("Year must be over 100") - } else if y > 200000 { - Error("Year must be less than 200000") - } else { - Ok(Js.Date.makeWithYM(~year=Belt.Float.fromInt(y), ~month=0.0, ())) - } - } let toString = Js.Date.toDateString let fromFloat = Js.Date.fromFloat let fmap = (t: t, fn: float => float) => t->toFloat->fn->fromFloat @@ -899,4 +887,22 @@ module Date = { } let addDuration = (t: t, duration: Duration.t) => fmap(t, t => t +. duration) let subtractDuration = (t: t, duration: Duration.t) => fmap(t, t => t -. duration) + //The Js.Date.makeWithYM function accepts a float, but only treats it as a whole number. + //Our version takes an integer to make this distinction clearer. + let makeWithYearInt = (y: int): result => { + if y < 100 { + Error("Year must be over 100") + } else if y > 200000 { + Error("Year must be less than 200000") + } else { + Ok(Js.Date.makeWithYM(~year=Belt.Float.fromInt(y), ~month=0.0, ())) + } + } + let makeFromYear = (year: float): result => { + let floor = year -> Js.Math.floor_float + makeWithYearInt(Belt.Float.toInt(floor))->R2.fmap(earlyDate => { + let diff = year -. floor + earlyDate->addDuration(diff *. Duration.year) + }) + } }