-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsolution_1.js
70 lines (62 loc) · 2.3 KB
/
solution_1.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
function solution(record) {
let history = [];
// looping
record.forEach(item => {
const splitRecord = item.split(' ');
const keyword = splitRecord[0];
const uid = splitRecord[1];
const name = splitRecord[2] ? splitRecord[2] : '';
switch (keyword) {
case 'Enter': {
// Check already left user with the uid, then change left user's nickName to new one
const existUser = history.find(item => item.user.uid === uid);
if (existUser) {
history = history.map(item => {
if (item.user.uid === uid) {
return {
...item,
user: { uid, name }
}
}
return item;
});
}
// Then push new user to the rooms with the uid
history.push({
user: { uid, name },
message: 'came in'
})
break;
}
case 'Leave': {
// Check user, then make him leave from rooms
const existIndex = history.findIndex(item => item.user.uid === uid);
if (existIndex > -1) {
const name = history[existIndex].user.nickName;
history.push({
user: { uid, name },
message: 'has left'
});
}
break;
}
case 'Change': {
// Change all user's nickName to new one with same uid
history = history.map(item => {
if (item.user.uid === uid) {
return {
...item,
user: { uid, name }
}
}
return item;
});
break;
}
default:
break;
}
});
return history.map(item => `${item.user.name} ${item.message}`);
}
console.log(solution(["Enter uid1234 Muzi", "Enter uid4567 Prodo", "Leave uid1234", "Enter uid1234 Prodo", "Change uid4567 Ryan"]));