Skip to content

Commit

Permalink
TimeSeries: add #<< convenience method
Browse files Browse the repository at this point in the history
Signed-off-by: Jimmy Tanagra <jcode@tanagra.id.au>
  • Loading branch information
jimtng authored and ccutrer committed Jul 21, 2024
1 parent 9db8d1d commit efa542b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/openhab/core/types/time_series.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,25 @@ def add(timestamp, state)
self
end

#
# Appends an entry to self, returns self
#
# @param [Array<Instant, State>] entry a two-element array with the timestamp and state.
# The timestamp can be an {Instant} or any object that responds to #to_zoned_date_time.
# @return [self]
#
# @example Append an entry
# time_series << [Time.at(2), 2]
#
def <<(entry)
raise ArgumentError, "entry must be an Array, but was #{entry.class}" unless entry.respond_to?(:to_ary)

entry = entry.to_ary
raise ArgumentError, "entry must be an Array of size 2, but was #{entry.size}" unless entry.size == 2

add(entry[0], entry[1])
end

private

def to_instant(timestamp)
Expand Down
11 changes: 11 additions & 0 deletions spec/openhab/core/types/time_series_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,17 @@
end
end

describe "#<<" do
it "works" do
ts << [Time.at(3), 3]
expect(ts.size).to be 3
expect(ts.first.state).to eql DecimalType.new(1)
expect(ts.begin).to eql Instant.of_epoch_second(1)
expect(ts.last.state).to eql DecimalType.new(3)
expect(ts.end).to eql Instant.of_epoch_second(3)
end
end

context "when accessed as an Array" do
it "is frozen" do
expect(ts.states).to be_frozen
Expand Down

0 comments on commit efa542b

Please sign in to comment.