From d8aff6caa4c9872de1d437faad00191c9d099a7a Mon Sep 17 00:00:00 2001 From: a14m Date: Mon, 30 Nov 2020 20:02:18 +0100 Subject: Add the cyclic plane (circular array) implementation w/testing --- CLI/ruby/lib/game_of_life/plane.rb | 27 ++++++++++++++++++++++++++ CLI/ruby/spec/plane_spec.rb | 39 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 CLI/ruby/lib/game_of_life/plane.rb create mode 100644 CLI/ruby/spec/plane_spec.rb (limited to 'CLI') diff --git a/CLI/ruby/lib/game_of_life/plane.rb b/CLI/ruby/lib/game_of_life/plane.rb new file mode 100644 index 0000000..f866754 --- /dev/null +++ b/CLI/ruby/lib/game_of_life/plane.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +module GameOfLife + # Custom Plane class that represent a cyclic/circular plane/array + # This class would always return an element unless the array is empty + class Plane < Array + # Extending the default array behaviour by treating the array as cyclic/circular object + # + # @example working with normal array + # a = [0, 1, 2, 3] + # a[-6] == a[-2] == a[2] + # a[-5] == a[-1] == a[3] + # a[-4] == a[0] == a[4] + # a[-3] == a[1] == a[5] + # a[-2] == a[2] == a[6] + # a[-1] == a[3] == a[7] + # a[0] == a[4] == a[8] + # + # @example working with empty array + # b = [] + # b[0] == b[1] == b[-1] == nil + def [](index) + return nil if empty? + super(index % size) + end + end +end diff --git a/CLI/ruby/spec/plane_spec.rb b/CLI/ruby/spec/plane_spec.rb new file mode 100644 index 0000000..c4efbb4 --- /dev/null +++ b/CLI/ruby/spec/plane_spec.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +RSpec.describe GameOfLife::Plane do + describe "#[]" do + context "when empty" do + subject { described_class.new } + + it "returns nil with [-1]" do + expect(subject[-1]).to be_nil + end + + it "returns nil with [0]" do + expect(subject[0]).to be_nil + end + + it "returns nil with [1]" do + expect(subject[1]).to be_nil + end + end + + context "when not empty" do + subject { described_class.new([0, 1, 2, 3]) } + + it "returns value at index" do + expect(subject[0]).to eq 0 + end + + it "returns value at -index (negative indices count backward from the end of the array)" do + expect(subject[-5]).to eq 3 + expect(subject[-1]).to eq 3 + end + + it "returns value at any index (indices bigger than size cycle again from the beginning)" do + expect(subject[5]).to eq 1 + expect(subject[9]).to eq 1 + end + end + end +end -- cgit v1.2.3