I have a system where I store chat messages in a dictionary with the date as the key and a list of messages as the value. Whenever a new message is added, the following code snippet is executed.
Is there a way to enhance the existing code to eliminate the use of JSON.parse and JSON.stringify?
on(MatchActions.AddMessage, (state: MatchState, payload: { message: Message }) => {
const messages: MessageDictionary = { ...state.chat.messages };
const keys = Object.keys(messages);
if (keys.length > 0) {
messages[keys[keys.length - 1]].push(payload.message);
} else {
messages[getNowUtc().toString()] = [payload.message];
}
return {
...state,
chat: {
...state.chat,
messages: messages
}
};
}),
export interface Chat {
chatId: string;
name: string;
messages: MessageDictionary;
}
export interface MessageDictionary {
[dateSendUtc: string]: Message[];
}
export interface Message {
chatId: string;
accountId: string;
messageId: string;
messageText: string;
messageSendUtc: Date;
fromMe: boolean;
}