# CREDIT Richard Laugesen

class Array

  # Pad an array with a given <tt>value</tt> upto a given <tt>length</tt>.
  #
  #   [0,1,2].pad(6,"a")  #=> [0,1,2,"a","a","a"]
  #   
  # If <tt>length</tt> is a negative number padding will be added
  # to the beginning of the array.
  #
  #   [0,1,2].pad(-6,"a")  #=> ["a","a","a",0,1,2]

  def pad(len, val=nil)
    return dup if self.size >= len.abs
    if len < 0
      Array.new((len+size).abs,val) + self
    else
      self + Array.new(len-size,val)
    end
  end

  # Like #pad but changes the array in place.
  #
  #    a = [0,1,2]
  #    a.pad!(6,"x")
  #    a  #=> [0,1,2,"x","x","x"]

  def pad!(len, val=nil)
    return self if self.size >= len.abs
    if len < 0
      replace Array.new((len+size).abs,val) + self
    else
      concat Array.new(len-size,val)
    end
  end

end


=begin test

  require 'test/unit'

  class TestPad < Test::Unit::TestCase

    def test_pad
      r = [0,1,2,3].pad(7,"x")
      x = [0,1,2,3,"x","x","x"]
      assert_equal(x,r)
    end

    def test_pad!
      a = [0,1,2,3]
      r = a.pad!(6,"y")
      x = [0,1,2,3,"y","y"]
      assert_equal(x,a)
    end

    def test_pad_negative
      r = [0,1,2,3].pad(-7,"n")
      x = ["n","n","n",0,1,2,3]
      assert_equal(x,r)
    end

    def test_pad_negative!
      a = [0,1,2,3]
      r = a.pad!(-6,"q")
      x = ["q","q",0,1,2,3]
      assert_equal(x,a)
    end

  end

=end

