Last active
April 4, 2019 08:29
-
-
Save huytd/ed8baeb45849b80d8e973d9d5e491f6e to your computer and use it in GitHub Desktop.
SlackStyleJoinLeftMessage created by huytd - https://repl.it/@huytd/SlackStyleJoinLeftMessage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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