Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/functional_support/core_ext/array.rb

Defined Under Namespace

Classes: ProductWithEmptyArray

Instance Method Summary collapse

Instance Method Details

#filter_map(&filter_block) ⇒ Object

Only apply map to things that successfully pass the filter, everything else is unchanged



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/functional_support/core_ext/array.rb', line 65

def filter_map(&filter_block)
  lambda do |&map_block|
    map do |element|
      if yield element
        map_block.call element 
      else
        element
      end
    end
  end
end

#headObject



16
17
18
# File 'lib/functional_support/core_ext/array.rb', line 16

def head
  self.take self.count - 1 unless self.count == 0
end

#in_repeated_groups_of(n = 1) ⇒ Object

Suppose n = 3, this takes something like [1,2,3,4,5] and splits it into something like the following:

[1,2,3], [2,3,4], [3,4,5]


42
43
44
45
46
# File 'lib/functional_support/core_ext/array.rb', line 42

def in_repeated_groups_of(n=1)
  return [self] if length == n
  return shift(nil).in_repeated_groups_of(n) if length < n
  [take(n)] + tail.in_repeated_groups_of(n)
end

#present_unshift(element = nil) ⇒ Object



48
49
50
51
# File 'lib/functional_support/core_ext/array.rb', line 48

def present_unshift(element=nil)
  unshift element if element.present?
  self
end

#product(xs) ⇒ Object

Returns the Cartesian product of two arrays



5
6
7
8
9
10
# File 'lib/functional_support/core_ext/array.rb', line 5

def product(xs)
  raise(ProductWithEmptyArray, "can't product #{self} with #{xs}") if count == 0 || xs.count == 0
  return xs.map { |x| [first, x] } if count == 1
  thing = xs.map { |x| [first, x] }
  thing + tail.product(xs)
end

#reduce_with_lookahead(*parameters, &reducer) ⇒ Object Also known as: inject_with_lookahead

same as reduce, except the reduction function can have arity > 2 with the second, third, etc. arguments being the lookahead



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/functional_support/core_ext/array.rb', line 22

def reduce_with_lookahead(*parameters, &reducer)
  case parameters.length
  when 0
    in_repeated_groups_of(reducer.arity - 1).reduce do |acc, arr|
      reducer.call acc, *arr
    end
  when 1
    init = parameters.first
    in_repeated_groups_of(reducer.arity - 1).reduce(init) do |acc, arr|
      reducer.call acc, *arr
    end
  else
    raise LocalJumpError, "no block given"
  end
end

#tailObject



12
13
14
# File 'lib/functional_support/core_ext/array.rb', line 12

def tail
  self[1..-1]
end

#uniq_merge(&block) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/functional_support/core_ext/array.rb', line 53

def uniq_merge(&block)
  lambda do |&merge_together|
    inject({}) do |hash, element|
      (hash[yield element] ||= []) << element
      hash
    end.to_a.map(&:last).inject(self.class.new) do |array, els|
      array.push els.reduce(&merge_together)
    end
  end
end