Sha256: 7161f9451367bb71228e828131d7533f1e175c1eb7a73c01294a3ddb20aaef61

Contents?: true

Size: 1.37 KB

Versions: 59

Compression:

Stored size: 1.37 KB

Contents

module Workarea
  class SwappableList
    include Enumerable

    delegate :to_s, to: :@source

    def initialize(source = [])
      @source = Array(source)
    end

    def insert(index, new_val)
      index = assert_index(index, :before)
      @source.insert(index, new_val)
    end
    alias_method :insert_before, :insert

    def insert_after(index, new_val)
      index = assert_index(index, :after)
      insert(index + 1, new_val)
    end

    def swap(target, new_val)
      index = assert_index(target, :before)
      insert(index, new_val)
      @source.delete_at(index + 1)
    end

    def delete(target)
      @source.delete(target)
    end

    def +(other)
      self.class.new(
        @source + Array(other)
      )
    end

    def -(other)
      self.class.new(
        @source - Array(other)
      )
    end

    def method_missing(method, *args, &block)
      if @source.respond_to?(method)
        @source.send(method, *args, &block)
      else
        super
      end
    end

    def respond_to_missing?(method_name, include_private = false)
      super || @source.respond_to?(method_name)
    end

    def deep_dup
      self.class.new(@source.deep_dup)
    end

    private

    def assert_index(index, where)
      i = index.is_a?(Integer) ? index : @source.index(index)
      raise "No such list item to insert #{where}: #{index.inspect}" unless i
      i
    end
  end
end

Version data entries

59 entries across 59 versions & 1 rubygems

Version Path
workarea-core-3.5.15 lib/workarea/swappable_list.rb
workarea-core-3.4.36 lib/workarea/swappable_list.rb
workarea-core-3.5.14 lib/workarea/swappable_list.rb
workarea-core-3.4.35 lib/workarea/swappable_list.rb
workarea-core-3.5.13 lib/workarea/swappable_list.rb
workarea-core-3.4.34 lib/workarea/swappable_list.rb
workarea-core-3.5.12 lib/workarea/swappable_list.rb
workarea-core-3.4.33 lib/workarea/swappable_list.rb
workarea-core-3.5.11 lib/workarea/swappable_list.rb
workarea-core-3.5.10 lib/workarea/swappable_list.rb
workarea-core-3.4.32 lib/workarea/swappable_list.rb
workarea-core-3.5.9 lib/workarea/swappable_list.rb
workarea-core-3.4.31 lib/workarea/swappable_list.rb
workarea-core-3.5.8 lib/workarea/swappable_list.rb
workarea-core-3.4.30 lib/workarea/swappable_list.rb
workarea-core-3.5.7 lib/workarea/swappable_list.rb
workarea-core-3.4.29 lib/workarea/swappable_list.rb
workarea-core-3.5.6 lib/workarea/swappable_list.rb
workarea-core-3.4.28 lib/workarea/swappable_list.rb
workarea-core-3.5.5 lib/workarea/swappable_list.rb