-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlogic.js
62 lines (53 loc) · 1.91 KB
/
logic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Part 1. Fill in any missing parts of the todoFunction object!
// you can access these on todo.todoFunctions
// For part one we expect you to use tdd
var todoFunctions = {
// todoFunctions.generateId() will give you a unique id
// You do not need to understand the implementation of this function.
generateId: (function() {
var idCounter = 0;
function incrementCounter() {
return (idCounter += 1);
}
return incrementCounter;
})(),
//cloneArrayOfObjects will create a copy of the todos array
//changes to the new array don't affect the original
cloneArrayOfObjects: function(todos) {
return todos.map(function(todo) {
return JSON.parse(JSON.stringify(todo));
});
},
addTodo: function(todos, newTodo) {
var allTodos = this.cloneArrayOfObjects(todos);
newTodo.id = this.generateId(); // generate fresh id for newTodo
newTodo.done = false;
allTodos.push(newTodo); // add newTodo to cloned array
return allTodos;
},
deleteTodo: function(todos, idToDelete) {
let allTodos = this.cloneArrayOfObjects(todos);
return allTodos.filter(x => x.id != idToDelete);
},
markTodo: function(todos, idToMark) {
var allTodos = this.cloneArrayOfObjects(todos);
allTodos.forEach(obj => {
if (obj.id == idToMark) {
obj.done = !obj.done;
}
});
return allTodos;
},
sortTodos: function(todos, sortFunction) {
let allTodos = this.cloneArrayOfObjects(todos);
allTodos.sort(sortFunction); // sorts todos clone *in place* according to sortFunction comparison test
return allTodos;
}
};
// Why is this if statement necessary?
// The answer has something to do with needing to run code both in the browser and in Node.js
// See this article for more details:
// http://www.matteoagosti.com/blog/2013/02/24/writing-javascript-modules-for-both-browser-and-node/
if (typeof module !== "undefined") {
module.exports = todoFunctions;
}