Last active
January 24, 2019 15:25
-
-
Save jacoyutorius/036687d2b449340313e4b4c6eaf447ab to your computer and use it in GitHub Desktop.
Array#override
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit' | |
# Array#override | |
# | |
# [0, 0, 0, 0, 0].override(['a', 'b']) | |
# => ['a', 'b', 0, 0, 0] | |
# | |
# [0, 0, 0, 0, 0].override(['a', 'b'], 2) | |
# => [0, 0, 'a', 'b', 0] | |
class Array | |
def override(array, shift=0) | |
_self = self.dup | |
_array = array.dup | |
_array.reject!.with_index{|_v, i| i >= _self.length } | |
_self.each.with_index(shift) do |_v, i| | |
break if i - shift >= _array.length | |
_self[i] = _array[i - shift] | |
end | |
_self.slice(0, self.length) | |
end | |
end | |
class ArrayTest < Test::Unit::TestCase | |
def test_override | |
ov = ['2018-11-1', '2018-12-1', '2019-1-1'] | |
assert_equal Array.new(10).fill(0).override(ov), ['2018-11-1', '2018-12-1', '2019-1-1', 0, 0, 0, 0, 0, 0, 0] | |
assert_equal Array.new(10).fill(0).override(ov, 2), [0, 0, '2018-11-1', '2018-12-1', '2019-1-1', 0, 0, 0, 0, 0] | |
assert_equal Array.new(2).fill(0).override(ov), ['2018-11-1', '2018-12-1'] | |
assert_equal Array.new(2).fill(0).override(ov, 1), [0, '2018-11-1'] | |
assert_equal Array.new(2).fill(0).override(ov, 2), [0, 0] | |
assert_equal Array.new(10).fill(0).override(ov, -2), ['2019-1-1', 0, 0, 0, 0, 0, 0, 0, '2018-11-1', '2018-12-1'] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment