Last active
December 15, 2017 12:48
-
-
Save victorhqc/eaf71d55422e334764e76e4c43297699 to your computer and use it in GitHub Desktop.
Angular 1.X Redux-Factory
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
(function(app) { | |
function TodoServiceFactory() { | |
var ADD_TODO = 'ADD_TODO'; | |
var REMOVE_TODO = 'REMOVE_TODO'; | |
var ID = -1; | |
function findIndex(haystack, needle) { | |
var isFound = false; | |
var index = -1; | |
haystack.some(function mapHaystack(data) { | |
index += 1; | |
isFound = needle(data, index); | |
return isFound; | |
}); | |
if (isFound) { | |
return index; | |
} | |
return -1; | |
} | |
function TodoService() { | |
this.ADD_TODO = ADD_TODO; | |
this.REMOVE_TODO = REMOVE_TODO; | |
} | |
TodoService.prototype.addTodo = function addTodoActionCreator(title, description) { | |
ID += 1; | |
return { | |
type: ADD_TODO, | |
payload: { | |
id: ID, | |
title: title, | |
description: description | |
} | |
}; | |
}; | |
TodoService.prototype.removeTodo = function removeTodoActionCreator(id) { | |
return { | |
type: REMOVE_TODO, | |
payload: { | |
id: id, | |
} | |
}; | |
} | |
TodoService.prototype.todosReducer = function todoReducer(state, action) { | |
state = state || []; | |
action = action || { type: '' }; | |
switch(action.type) { | |
case ADD_TODO: | |
return state.concat([{ | |
id: action.payload.id, | |
title: action.payload.title, | |
description: action.payload.description, | |
createdAt: Date.now() | |
}]); | |
case REMOVE_TODO: | |
var index = findIndex(state, function findTodoIndex(todo) { | |
return todo.id === action.payload.id; | |
}); | |
// This removes the element from the array, without mutating the original state. | |
return state | |
.slice(0, index) | |
.concat(state.slice(index + 1, state.length)); | |
default: | |
return state; | |
} | |
}; | |
return new TodoService(); | |
} | |
app.factory('TodoService', TodoServiceFactory); | |
})(myApp); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment