Last active
July 14, 2018 04:50
-
-
Save baweaver/83e2d70d54d45bbcdf6e1a357982c345 to your computer and use it in GitHub Desktop.
Going over https://medium.com/@roman01la/understanding-transducers-in-javascript-3500d3bd9624 in Ruby
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
# Do note that I'm being purposely verbose to make this easier to read through, | |
# as transducers are already a bit hard to grok without shorthanding things. | |
def maps(&function) | |
proc { |accumulator, value| | |
accumulator << function.call(value) | |
} | |
end | |
def filters(&function) | |
proc { |accumulator, value| | |
if function.call(value) | |
accumulator << value | |
else | |
accumulator | |
end | |
} | |
end | |
[1,2,3,4,5] | |
.reduce([], &maps { |v| v * 3 }) | |
.reduce([], &filters { |v| v.even? }) | |
# => [6, 12] | |
def mapping(&function) | |
proc { |reducing_function| | |
proc { |accumulator, value| | |
reducing_function.call(accumulator, function.call(value)) | |
} | |
} | |
end | |
def filtering(&function) | |
proc { |reducing_function| | |
proc { |accumulator, value| | |
if function.call(value) | |
reducing_function.call(accumulator, value) | |
else | |
accumulator | |
end | |
} | |
} | |
end | |
concats = proc { |accumulator, value| accumulator << value } | |
[1,2,3,4,5] | |
.reduce([], &mapping { |v| v * 3 }.call(concats)) | |
.reduce([], &filtering { |v| v.even? }.call(concats)) | |
# => [6, 12] | |
# gem install ramda-ruby | |
require 'ramda' | |
[1,2,3,4,5].reduce([], &Ramda.pipe( | |
mapping { |v| v + 1 }, | |
filtering { |v| v.even? }, | |
mapping { |v| v * 3 } | |
).call(concats)) | |
# => [7, 13] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment