Skip to content

Instantly share code, notes, and snippets.

@srph
Created June 6, 2019 08:56
Show Gist options
  • Select an option

  • Save srph/88b0515a788d48ee086fd4bc16be9709 to your computer and use it in GitHub Desktop.

Select an option

Save srph/88b0515a788d48ee086fd4bc16be9709 to your computer and use it in GitHub Desktop.
JS: Group chat messages based on criteria (initial code for Care.tv)
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