Class: Reducers::Reducible

Inherits:
Object
  • Object
show all
Includes:
Transformers
Defined in:
lib/reducers.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Transformers

#drop, #drop_while, #duplicate_on, #flat_map, #grep, #group_by, #map, #mapcat, #mash, #reject, #select, #take, #take_while, #to_a

Constructor Details

#initialize(coll) ⇒ Reducible

Returns a new instance of Reducible.



259
260
261
262
263
# File 'lib/reducers.rb', line 259

def initialize(coll)
  @coll = coll
  @chain = ->x{x}
  @proc_chain = []
end

Instance Attribute Details

#collObject (readonly)

attr_reader :chain



257
258
259
# File 'lib/reducers.rb', line 257

def coll
  @coll
end

#proc_chainObject (readonly)

attr_reader :chain



257
258
259
# File 'lib/reducers.rb', line 257

def proc_chain
  @proc_chain
end

Instance Method Details

#chainObject



303
304
305
# File 'lib/reducers.rb', line 303

def chain
  chain ||= Proc.compose(proc_chain)
end

#forceObject



308
309
310
# File 'lib/reducers.rb', line 308

def force
  reduce([]){|r,i| r << i ; r}
end

#initialize_copy(source) ⇒ Object



288
289
290
291
# File 'lib/reducers.rb', line 288

def initialize_copy(source)
  super
  @proc_chain = @proc_chain.dup
end

#partition(&block) ⇒ Object



298
299
300
301
# File 'lib/reducers.rb', line 298

def partition(&block)
  p1,p2 = tee
  [p1.select(&block), p2.reject(&block)]
end

#reduce(init = nil, f = Undefined, &block) ⇒ Object



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/reducers.rb', line 265

def reduce(init = nil, f= Undefined ,&block)
  if !block or !f == Undefined
    if f == Undefined
      f = init
      init = nil
    end

    reducer = f
  else
    reducer = chain.(block) if f == Undefined
  end

  result = catch(:reduced){

    if init
      coll.reduce(init,&reducer)
    else
      coll.reduce(&reducer)
    end
  }

end

#teeObject



293
294
295
296
# File 'lib/reducers.rb', line 293

def tee
  p2 = self.dup
  [self, p2]
end