Last active
October 22, 2020 03:59
-
-
Save huytd/7ed3521bc1bbe4b5086d176fda85fec8 to your computer and use it in GitHub Desktop.
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
// Run it online at: | |
// https://algorithm-pad.now.sh/?gist=https://gist.githubusercontent.com/huytd/7ed3521bc1bbe4b5086d176fda85fec8/raw/6019ff8e19ec8278ac55a21b3cbf43ef54ff1882/slack-style-join-left-message-run.js | |
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" | |
} | |
]; | |
debug(data); | |
const groupByUser = data => data.reduce((r, i) => { | |
if (!r[i.user]) r[i.user] = i.action; | |
else r[i.user] -= i.action; | |
debug(r); | |
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); | |
debug(r[act]); | |
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}`; | |
}; | |
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
https://gist.github.com/huytd/7ed3521bc1bbe4b5086d176fda85fec8#file-slack-style-join-left-message-run-js-L3-L4
You should use past tense too.