Last active
June 3, 2016 11:06
-
-
Save theozaurus/354c755470b1ef7e1c34234c90567f9e to your computer and use it in GitHub Desktop.
Lazy streams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class A | |
def initialize(*processors) | |
@processors = processors | |
end | |
def call(list) | |
@processors.inject(0) { |acc, p| | |
acc + p.call(list) | |
} | |
end | |
end | |
class B | |
def initialize(multiplier) | |
@multiplier = multiplier | |
end | |
def call(list) | |
list.map { |i| | |
i * @multiplier | |
}.inject(0) { |acc, i| | |
puts "B with multipler: #{@multiplier}, adding: #{i}" | |
acc + i | |
} | |
end | |
end | |
A.new(B.new(1), B.new(2)).call([1, 2, 3, 4, 5].lazy) | |
# => 45 | |
# B with multipler: 1, adding: 1 | |
# B with multipler: 1, adding: 2 | |
# B with multipler: 1, adding: 3 | |
# B with multipler: 1, adding: 4 | |
# B with multipler: 1, adding: 5 | |
# B with multipler: 2, adding: 2 | |
# B with multipler: 2, adding: 4 | |
# B with multipler: 2, adding: 6 | |
# B with multipler: 2, adding: 8 | |
# B with multipler: 2, adding: 10 | |
# Desired output | |
# => 45 | |
# B with multipler: 1, adding: 1 | |
# B with multipler: 2, adding: 2 | |
# B with multipler: 1, adding: 2 | |
# B with multipler: 2, adding: 4 | |
# B with multipler: 1, adding: 3 | |
# B with multipler: 2, adding: 6 | |
# B with multipler: 1, adding: 4 | |
# B with multipler: 2, adding: 8 | |
# B with multipler: 1, adding: 5 | |
# B with multipler: 2, adding: 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment