@huytd/

SlackStyleJoinLeftMessage

Nodejs

No description

fork
loading
Files
  • index.js
index.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
const Join  = 1;
const Leave = -1;
const JoinedAndLeft = 2;
const Rejoined = -2;

const toStatus = n => {
  switch (n) {
    case Join: return 'joined';
    case Leave: return 'left';
    case JoinedAndLeft: return 'joined and left';
    case Rejoined: return 'rejoined';
  }
};

const data = [
  {
    action: Join,
    user: "Huy"
  },
  {
    action: Leave,
    user: "Cam"
  },
  {
    action: Leave,
    user: "Huy"
  },
  {
    action: Join,
    user: "Cam"
  },
  {
    action: Join,
    user: "Noob"
  },
  {
    action: Join,
    user: "Kcjpop"
  }
];

const groupByUser = data => data.reduce((r, i) => {
  if (!r[i.user]) r[i.user] = i.action;
  else r[i.user] -= i.action;
  return r;
}, {});

const groupByAction = data => {
  return Object.keys(data).map(user => ({
    user: user,
    action: data[user]
  })).reduce((r, i) => {
    const act = toStatus(i.action);
    if (!r[act]) r[act] = {
      action: act,
      users: []
    };
    r[act].users.push(i.user);
    return r;
  }, {});
};

const entryToStr = e => {
  if (e.users.length > 1) {
    const first = e.users.shift();
    return `${first} ${e.action} along with ${e.users.join(', ')}`;
  } else {
    return `${e.users.join(', ')} ${e.action}`;
  }
}

const translate = arr => {
  let r = [];
  for (const e in arr) { 
    r.push(entryToStr(arr[e]));
  }
  const last = r.pop();
  return `${r.join(', ')}, also, ${last}`;
};

console.log(translate(groupByAction(groupByUser(data))));
// Huy joined and left, Cam rejoined, also, Noob joined along with Kcjpop