-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
72 lines (61 loc) · 1.66 KB
/
utils.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
63
64
65
66
67
68
69
70
71
72
import { v4 as uuid } from 'uuid';
export const createIdea = (state, rootState) => {
const { title, description, tags } = state;
const { loggedInUser: { emp_id: createdBy } } = rootState;
return {
id: uuid(),
title,
description,
tags,
createdBy,
createdAt: new Date()
}
}
export const createUpvote = (rootState, ideaId) => {
const { loggedInUser: { emp_id: userId } } = rootState;
return {
id: uuid(),
userId,
ideaId
}
}
export const addToStorage = (item, itemToAdd) => {
const list = [...getStorage(item), itemToAdd];
return _updateStorage(item, list);
}
export const getStorage = item => {
const list = localStorage.getItem(item);
return list ? JSON.parse(list) : [];
}
export const removeUpvoteFromStorage = (item, id, rootState) => {
const { loggedInUser: { emp_id: userId } } = rootState;
const list = getStorage(item).filter(p => {
if (p.ideaId !== id) {
return true;
}
if (p.userId !== userId) {
return true;
}
return false;
});
return _updateStorage(item, list);
}
export const sortBy = (upvotesState) => {
const createdAt = _sortByCreatedAt;
const upvotes = _sortByUpvotes(upvotesState);
return {
createdAt,
upvotes
}
};
const _sortByCreatedAt = (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
const _sortByUpvotes = (upvotes) => {
return function(a, b) {
return _getVotesCount(b, upvotes) - _getVotesCount(a, upvotes);
}
}
const _getVotesCount = (idea, upvotes) => upvotes.filter(uv => uv.ideaId === idea.id).length
const _updateStorage = (item, list) => {
localStorage.setItem(item, JSON.stringify(list));
return list;
}