Class: Array

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

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



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/functional_support/core_ext/array.rb', line 56

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



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

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]


33
34
35
36
37
# File 'lib/functional_support/core_ext/array.rb', line 33

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



39
40
41
42
# File 'lib/functional_support/core_ext/array.rb', line 39

def present_unshift(element=nil)
  unshift element if element.present?
  self
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



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/functional_support/core_ext/array.rb', line 13

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



3
4
5
# File 'lib/functional_support/core_ext/array.rb', line 3

def tail
  self[1..-1]
end

#uniq_merge(&block) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/functional_support/core_ext/array.rb', line 44

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