Created
June 6, 2019 08:56
-
-
Save srph/88b0515a788d48ee086fd4bc16be9709 to your computer and use it in GitHub Desktop.
JS: Group chat messages based on criteria (initial code for Care.tv)
This file contains hidden or 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
| interface AppPartyLog { | |
| id: number | |
| party_id: number | |
| type: 'activity' | 'message' | |
| activity?: { | |
| id: string | |
| text: string | |
| user: AppUser | |
| } | |
| message?: { | |
| id: string | |
| text: string | |
| user: AppUser | |
| } | |
| created_at: string | |
| updated_at: string | |
| } | |
| interface GroupedLog { | |
| type: 'activity' | 'message' | |
| user: AppUser | |
| logs: AppPartyLog[] | |
| } | |
| /** | |
| * This will group chat based on the criteria: | |
| * | |
| * Suceeding logs | |
| * Succeeding messages sent by the same user | |
| */ | |
| function groupPartyLogs(logs: AppPartyLog[]): GroupedLog[] { | |
| if (logs.length === 0) { | |
| return [] | |
| } | |
| const first: AppPartyLog = logs[0] | |
| const groups: GroupedLog[] = [{ | |
| type: first.type, | |
| user: first[first.type].user, | |
| logs: [first] | |
| }] | |
| // Since we've initialized the group with the first log, we'll start with the second log. | |
| logs.slice(1).forEach(log => { | |
| const recent = last(groups) | |
| // We'll group it together based on the criteria | |
| if (recent.type === 'activity' || recent.user.id === log.message.user.id) { | |
| recent.logs.push(log) | |
| } else { | |
| // Otherwise, it probably belongs to its own group | |
| groups.push({ | |
| type: log.type, | |
| user: log[log.type].user, | |
| logs: [log] | |
| }) | |
| } | |
| }) | |
| return groups | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment