Skip to content

Commit

Permalink
add createReducer (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
AmaranthineCodices authored and LPGhatguy committed Mar 4, 2018
1 parent 9efe558 commit b77f135
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/createReducer.lua
@@ -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
@@ -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
@@ -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,
}

0 comments on commit b77f135

Please sign in to comment.