client/src/Helpers/most-recent-only.ts
import { INFO_MESSAGE_CLIPPED, MAPPING_MESSAGE, MAPPING_MESSAGE_DELTA } from 'src/config'
import { Message, MessageChannel, MessageCustom, MessageInfoTypeClipped } from 'src/custom-types'
/** helper function to produce unique ids for channel messages
*/
const getIDs = (message: MessageChannel): string => {
let res
const generalMessage = message as any as Message
const isNotMapping = !(generalMessage.messageType === MAPPING_MESSAGE || generalMessage.messageType === MAPPING_MESSAGE_DELTA)
const customMessage = message as any as MessageCustom
const emptyNonMappingMessage = isNotMapping && customMessage.message === undefined
if (message.messageType === INFO_MESSAGE_CLIPPED || ('infoType' in message && message.infoType === true) || emptyNonMappingMessage) {
const clippedMessage = message as MessageInfoTypeClipped
res = '' + clippedMessage.gameTurn
} else {
const msg = message.message
if (msg && msg.Reference !== undefined) {
// note: `Reference` is the id generated by Serge for Collab-style messages
res = msg.Reference
} else {
res = message._id
}
}
return res
}
const uniqByKeepLast = (data: MessageChannel[], key: (message: MessageChannel) => string) => {
return [
...new Map(
data.map(x => [key(x), x])
).values()
]
}
/** helper function to reduce the list of messages by removing duplicate
* turn markers & older versions of messages with reference numbers
*/
const mostRecentOnly = (messages: MessageChannel[]): MessageChannel[] => {
return uniqByKeepLast(messages, getIDs)
}
export default mostRecentOnly