Archived
1
0
Fork 0
This repository has been archived on 2023-03-27. You can view files and clone it, but cannot push or open issues or pull requests.
cli-old/lib/obredux.rb

74 lines
1.2 KiB
Ruby
Raw Normal View History

2017-07-27 20:33:32 -04:00
# frozen_string_literal: true
module Obredux
2017-07-27 23:51:44 -04:00
UNDEFINED = {}.freeze
2017-07-27 21:47:18 -04:00
2017-07-27 20:33:32 -04:00
class Action; end
2017-07-27 21:47:18 -04:00
class Init < Action; end
class Store
2017-07-27 22:27:42 -04:00
attr_reader :reducer_klass, :state
2017-07-27 21:47:18 -04:00
2017-07-27 22:27:42 -04:00
def initialize(reducer_klass)
@reducer_klass = reducer_klass
@state = UNDEFINED
dispatch Init.new
2017-07-27 21:47:18 -04:00
end
def dispatch(action)
2017-07-27 22:27:42 -04:00
@state = reducer_klass.new(state, action).call
2017-07-27 21:47:18 -04:00
end
end
class Reducer
2017-07-27 23:51:44 -04:00
def self.combine(options = nil)
@combine ||= {}
return @combine if options.nil?
options.each do |key, reducer_klass|
@combine[key] = reducer_klass
end
end
def initialize(state, action)
@state = state
@action = action
end
def call
2017-07-27 23:51:44 -04:00
init = state.equal? UNDEFINED
2017-07-27 23:42:52 -04:00
@state ||= {}.freeze
2017-07-27 23:51:44 -04:00
unless self.class.combine.empty?
@state = state.merge(
self.class.combine.map do |key, reducer_klass|
[
key,
reducer_klass.new(state[key], action).call,
]
end.to_h.freeze,
).freeze
end
@state = state.merge initial_state if init
reduce
end
private
attr_reader :state, :action
def initial_state
2017-07-27 23:44:24 -04:00
{}.freeze
end
2017-07-27 23:42:52 -04:00
def reduce
2017-07-27 23:44:24 -04:00
state
2017-07-27 23:42:52 -04:00
end
end
2017-07-27 20:33:32 -04:00
end