Skip to content

Commit 3d48a76

Browse files
Merge pull request clj-time#143 from siscia/periodic-add
Periodic add
2 parents dddd99c + e352b8d commit 3d48a76

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

src/clj_time/periodic.clj

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
(ns clj-time.periodic
2-
(:require [clj-time.internal.fn :as ifns]
3-
[clj-time.core :as ct])
2+
(:require [clj-time.core :as ct])
43
(:import [org.joda.time DateTime ReadablePeriod Period]))
54

65
(defn periodic-seq
7-
"Returns an infinite sequence of date-time values growing over specific period"
8-
[^DateTime start ^ReadablePeriod period-like]
9-
(let [^Period period (.toPeriod period-like)]
10-
(map (fn [^long i]
11-
(ct/plus start (.multipliedBy period i)))
12-
(iterate inc 0))))
6+
"Returns a sequence of date-time values growing over specific period.
7+
The 2 argument function takes as input the starting value and the growing value,
8+
returning a lazy infinite sequence.
9+
The 3 argument function takes as input the starting value, the upper bound value,
10+
and the growing value, return a lazy sequence."
11+
([^DateTime start ^ReadablePeriod period-like]
12+
(let [^Period period (.toPeriod period-like)]
13+
(map (fn [i]
14+
(ct/plus start (.multipliedBy period i)))
15+
(iterate inc 0))))
16+
([^DateTime start ^DateTime end ^ReadablePeriod period-like]
17+
(let [^Period period (.toPeriod period-like)]
18+
(take-while (fn [^DateTime next]
19+
(ct/before? next end))
20+
(periodic-seq start period-like)))))

test/clj_time/periodic_test.clj

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,16 @@
3333
d1 (second uds)
3434
d2 (nth uds 2)
3535
d3 (nth uds 3))))
36+
37+
(deftest test-limited-periodic-sequence
38+
(let [d0 (date-time 2014 1 31)
39+
d1 (date-time 2014 2 28)
40+
d2 (date-time 2014 3 31)
41+
d3 (date-time 2014 4 30)
42+
uds (periodic-seq d0 d3 (months 1))]
43+
(are [a b] (= a b)
44+
d0 (first uds)
45+
d1 (second uds)
46+
d2 (nth uds 2))
47+
(are [i] (thrown? IndexOutOfBoundsException (nth uds i)) 3)))
48+

0 commit comments

Comments
 (0)