Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add createReducer #10

Merged
merged 2 commits into from
Mar 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions lib/createReducer.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
return function(initialState, handlers)
return function(state, action)
if state == nil then
return initialState
end

local handler = handlers[action.type]

if handler then
return handler(state, action)
end

return state
end
end
79 changes: 79 additions & 0 deletions lib/createReducer.spec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
return function()
local createReducer = require(script.Parent.createReducer)

it("should handle actions", function()
local reducer = createReducer({
a = 0,
b = 0,
}, {
a = function(state, action)
return {
a = state.a + 1,
b = state.b
}
end,
b = function(state, action)
return {
a = state.a,
b = state.b + 2,
}
end,
})

local newState = reducer({
a = 0,
b = 0,
}, {
type = "a"
})

expect(newState.a).to.equal(1)

newState = reducer(newState, {
type = "b"
})

expect(newState.b).to.equal(2)
end)

it("should return the initial state if the state is nil", function()
local reducer = createReducer({
a = 0,
b = 0,
-- We don't care about the actions here
}, {})

local newState = reducer(nil, {})
expect(newState).to.be.ok()
expect(newState.a).to.equal(0)
expect(newState.b).to.equal(0)
end)

it("should return the same state if the action is not handled", function()
local initialState = {
a = 0,
b = 0,
}

local reducer = createReducer(initialState, {
a = function(state, action)
return {
a = state.a + 1,
b = state.b
}
end,
b = function(state, action)
return {
a = state.a,
b = state.b + 2,
}
end,
})

local newState = reducer(initialState, {
type = "c"
})

expect(newState).to.equal(initialState)
end)
end
2 changes: 2 additions & 0 deletions lib/init.lua
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
local Store = require(script.Store)
local createReducer = require(script.createReducer)
local combineReducers = require(script.combineReducers)

return {
Store = Store,
createReducer = createReducer,
combineReducers = combineReducers,
}