From 76655750522040c1ac149ee869b7b94490f320d0 Mon Sep 17 00:00:00 2001 From: Pedro Correa Date: Thu, 22 May 2025 13:20:29 -0300 Subject: [PATCH] :sparkles: (Janet) chapter 8 --- Janet/chapter8/counter.janet | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Janet/chapter8/counter.janet diff --git a/Janet/chapter8/counter.janet b/Janet/chapter8/counter.janet new file mode 100644 index 0000000..7722951 --- /dev/null +++ b/Janet/chapter8/counter.janet @@ -0,0 +1,29 @@ +(def counter-prototype + @{:add (fn [self amount] (+= (self :_count) amount)) + :increment (fn [self] (:add self 1)) + :count (fn [self] (self :_count))}) + +(defn new-counter [] + (table/setproto @{:_count 0} counter-prototype)) + +(def counter (new-counter)) + +(print (:count counter)) +(:increment counter) +(print (:count counter)) +(:add counter 3) +(print (:count counter)) + +(def Counter + (let [proto @{:add (fn [self amount] (+= (self :_count) amount)) + :increment (fn [self] (:add self 1)) + :count (fn [self] (self :_count))}] + (fn [] (table/setproto @{:_count 0} proto)))) + +(def counter (Counter)) +(print (:count counter)) +(:increment counter) +(print (:count counter)) +(:add counter 3) +(print (:count counter)) + -- 2.51.2