Module: Polyfill::V2_2::Enumerable

Defined in:
lib/polyfill/v2_2/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#max(n = nil) ⇒ Object

Raises:

  • (ArgumentError)


4
5
6
7
8
9
10
# File 'lib/polyfill/v2_2/enumerable.rb', line 4

def max(n = nil)
  return block_given? ? super(&::Proc.new) : super() if n.nil? || n == 1

  raise ArgumentError, "negative size (#{n})" if n < 0

  (block_given? ? sort(&::Proc.new) : sort).last(n).reverse
end

#max_by(n = nil) ⇒ Object

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
# File 'lib/polyfill/v2_2/enumerable.rb', line 12

def max_by(n = nil)
  if n.nil? || n == 1 || !block_given?
    return block_given? ? super(&::Proc.new) : super()
  end

  raise ArgumentError, "negative size (#{n})" if n < 0

  sort_by(&::Proc.new).last(n).reverse
end

#min(n = nil) ⇒ Object

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
# File 'lib/polyfill/v2_2/enumerable.rb', line 22

def min(n = nil)
  return block_given? ? super(&::Proc.new) : super() if n.nil? || n == 1

  raise ArgumentError, "negative size (#{n})" if n < 0

  (block_given? ? sort(&::Proc.new) : sort).first(n)
end

#min_by(n = nil) ⇒ Object

Raises:

  • (ArgumentError)


30
31
32
33
34
35
36
37
38
# File 'lib/polyfill/v2_2/enumerable.rb', line 30

def min_by(n = nil)
  if n.nil? || n == 1 || !block_given?
    return block_given? ? super(&::Proc.new) : super()
  end

  raise ArgumentError, "negative size (#{n})" if n < 0

  sort_by(&::Proc.new).first(n)
end

#slice_after(pattern = nil) ⇒ Object

Raises:

  • (ArgumentError)


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/polyfill/v2_2/enumerable.rb', line 40

def slice_after(pattern = nil)
  raise ArgumentError, 'both pattern and block are given' if pattern && block_given?
  raise ArgumentError, 'wrong number of arguments (given 0, expected 1)' if !pattern && !block_given?

  matcher = pattern || ::Proc.new

  ::Enumerator.new do |yielder|
    output = []
    each do |element, *rest|
      elements = rest.any? ? [element, *rest] : element

      output.push(elements)
      if matcher === output.last # rubocop:disable Style/CaseEquality
        yielder << output
        output = []
      end
    end
    yielder << output unless output.empty?
  end
end

#slice_whenObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/polyfill/v2_2/enumerable.rb', line 61

def slice_when
  block = ::Proc.new

  ::Enumerator.new do |yielder|
    output = []
    each do |element, *rest|
      elements = rest.any? ? [element, *rest] : element

      if output.empty? || !block.call(output.last, elements)
        output.push(elements)
      else
        yielder << output
        output = [elements]
      end
    end
    yielder << output unless output.empty?
  end
end