Sha256: f72cd7d6b4313d8492abea5e4645d03e5738584aad3bb0b867e95d78af489b9f

Contents?: true

Size: 1.31 KB

Versions: 3

Compression:

Stored size: 1.31 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

    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

3 entries across 3 versions & 1 rubygems

Version Path
workarea-core-3.4.14 lib/workarea/swappable_list.rb
workarea-core-3.4.13 lib/workarea/swappable_list.rb
workarea-core-3.4.12 lib/workarea/swappable_list.rb