From dee31024f0421ca9f0bb041037af902fb40b81c6 Mon Sep 17 00:00:00 2001 From: arctic-hen7 Date: Fri, 12 May 2023 09:47:21 +1000 Subject: [PATCH] feat: added `get_seconds_since_epoch()` Fixes #1. --- README.md | 4 +++- src/lib.rs | 12 ++++++++++++ src/methods/speed-v1.rhai | 1 + 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d89e641..c7866c8 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,9 @@ Method scripts are a little more complicated than adapter scripts, as they need 3. A function `adjust_card(response, data, difficult) -> [..., bool]`, which takes in the user's response to a card (guaranteed to be one of the ones you defined in `const RESPONSES`), the card's data, and whether or not it is marked as difficult. It should return the new data (this is where you update the properties that you use to determine a card's weight) and whether or not the card should now be marked as difficult. Note that the meaning of 'difficult' is entirely method-dependent, and it is simply one of the ways Forne lets users see how they're doing with their sets. 4. A function `get_default_metadata() -> ...`, which should return the default values you want to use for a card's `data`. -As an example to help you understand all this a bit better, here's a very naive learning method with heavy commenting: +If your method depends on scheduling when a card should next be reviewed, you can get a representation of the time with `get_seconds_since_epoch`, which returns the number of seconds since Unix Epoch (Jan. 1 1970), which will be negative if you've done a bit of time travel. + +As an example to help you understand all this a bit better, here's a very naive learning method: ```rhai const RESPONSES = ["y", "n"]; diff --git a/src/lib.rs b/src/lib.rs index 6268a55..4df9a98 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,6 +13,7 @@ pub use set::*; use anyhow::Result; use fancy_regex::Regex; use rhai::{Dynamic, Engine, EvalAltResult}; +use std::time::SystemTime; /// A Forne engine, which can act as the backend for learn operations. An instance of this `struct` should be /// instantiated with a [`Set`] to operate on and an operation to perform. @@ -155,6 +156,17 @@ impl Forne { Ok::<_, Box>(Dynamic::from_array(pairs)) }, ); + // Support for working with timestamps + engine.register_fn( + "get_seconds_since_epoch", // Gets the number of *seconds* since Unix epoch + || { + match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) { + Ok(duration) => duration.as_secs() as i64, + // If we're before 01/01/1970...well ok then! + Err(err) => err.duration().as_secs() as i64 * -1, + } + }, + ); engine } diff --git a/src/methods/speed-v1.rhai b/src/methods/speed-v1.rhai index 43c7dcc..9b608b7 100644 --- a/src/methods/speed-v1.rhai +++ b/src/methods/speed-v1.rhai @@ -1,6 +1,7 @@ const RESPONSES = ["y", "n"]; fn get_weight(data, difficult) { + print(get_seconds_since_epoch()); return data.weight; } fn adjust_card(res, data, difficult) {