Skip to content

Commit

Permalink
Improve streaming logic
Browse files Browse the repository at this point in the history
  • Loading branch information
divyanshu013 committed Feb 17, 2018
1 parent d495ae3 commit 13ed7b7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 41 deletions.
5 changes: 4 additions & 1 deletion components/TodoItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ class TodoItem extends Component {
flexDirection: 'row',
}}
>
<CheckBox checked={todo.completed} />
<CheckBox
checked={todo.completed}
onPress={() => this.onTodoItemToggle(todo, onUpdate)}
/>
<Body
style={{
flex: 1,
Expand Down
52 changes: 12 additions & 40 deletions utils/index.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,18 @@
class Utils {
// [source] https://gist.github.com/lmfresneda/9158e06a93a819a78b30cc175573a8d3
static removeDuplicates = (arr, prop) => {
const obj = {};
for (let i = 0, len = arr.length; i < len; i++) {
if (!obj[arr[i][prop]]) obj[arr[i][prop]] = arr[i];
}
const newArr = [];
for (const key in obj) newArr.push(obj[key]); // eslint-disable-line
return newArr;
};

static mergeTodos(todos, streamData) {
// note: don't judge for the logic
let todosData = todos;
if (todosData.length > 0 || streamData.length > 0) {
todosData = todosData.map((todo) => {
let todoToReturn = todo;
for (let i = 0; i < streamData.length; i++) {
// variable to track untouched todos after checking with all todosData iems
streamData[i].touched = false; // eslint-disable-line
// [case]: todo data is updated
if (todo._id === streamData[i]._id) {
todoToReturn = streamData[i];
streamData[i].touched = true; // eslint-disable-line
}
}
return todoToReturn;
});
// [case]: new todo is added
// collect untouched todos || the newly added streamed todos
const newTodos = streamData.filter(todo => !todo.touched);
// merge the new streaming data with updated streaming data
if (newTodos.length > 0) todosData = todosData.concat(newTodos);
// clean unpredictable duplicates
todosData = this.removeDuplicates(todosData, '_id');
// clean deleted todos
todosData = todosData.filter(todo => !todo._deleted);
}
// sorting todos based on creation time
todosData = todosData.sort((a, b) => a.createdAt - b.createdAt);
// generate an array of ids of streamData
const streamDataIds = streamData.map(todo => todo._id);

return todosData;
return todos
// consider streamData as the source of truth
// first take existing todos which are not present in stream data
.filter(({ _id }) => !streamDataIds.includes(_id))
// then add todos from stream data
.concat(streamData)
// remove todos which are deleted in stream data
.filter(todo => !todo._deleted)
// finally sort on the basis of creation timestamp
.sort((a, b) => a.createdAt - b.createdAt);
}
}

Expand Down

0 comments on commit 13ed7b7

Please sign in to comment.