Skip to content

Instantly share code, notes, and snippets.

@victorhqc
Last active December 15, 2017 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorhqc/eaf71d55422e334764e76e4c43297699 to your computer and use it in GitHub Desktop.
Save victorhqc/eaf71d55422e334764e76e4c43297699 to your computer and use it in GitHub Desktop.
Angular 1.X Redux-Factory
(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