Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SlackStyleJoinLeftMessage created by huytd - https://repl.it/@huytd/SlackStyleJoinLeftMessage
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.