-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtankService.js
125 lines (93 loc) · 2.02 KB
/
tankService.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
var _ = require('underscore');
var tanks = [];
var createUser = function(tank, userId) {
var user = {
userId: userId,
items: []
};
tank.items.forEach(addUserItem.bind(null, user));
return user;
};
var createItem = function(item) {
return _.extend(item, {
_id: _.uniqueId()
});
}
var get = function(id) {
return _.findWhere(tanks, {
id: id
});
};
var getUser = function(tank, userId) {
return tank && _.findWhere(tank.users, {
userId: userId
});
};
var addUserItem = function(user, item) {
var positions = _.pluck(user.items, 'relativePosition');
var top = positions.length ? Math.min.apply(null, positions) : Number.MAX_SAFE_INTEGER;
var buffer = 10000;
user.items.push({
itemId: item._id,
list: 'bank',
relativePosition: top - buffer
});
};
exports.create = function(tank, userId) {
_.extend(tank, {
id: _.uniqueId(),
items: [],
users: []
});
var user = createUser(tank, userId);
tanks.push(tank);
tank.users.push(user);
return tank;
};
exports.get = get;
exports.getAll = function() {
return tanks;
};
exports.getTankUsers = function(id) {
var tank = get(id);
return tank && tank.users;
};
exports.addTankUser = function(id, userId) {
var tank = get(id);
if (!tank) {
return;
}
var existingUser = getUser(tank, userId);
if (existingUser) {
return existingUser;
}
var user = createUser(tank, userId);
tank.users.push(user)
return user;
};
exports.getTankUser = function(id, userId) {
return getUser(get(id), userId);
};
exports.getTankUserItems = function(id, userId) {
var user = getUser(get(id), userId);
return user && user.items;
};
exports.addTankItem = function(id, data) {
if (!_.isObject(data)) {
return;
}
var tank = get(id);
if (!tank) {
return;
}
var item = createItem(data);
tank.items.push(item);
tank.users.forEach(function(user) {
addUserItem(user, item);
});
return item;
};
exports.getTankItems = function(id) {
var tank = get(id);
return tank && tank.items;
};