【发布时间】:2021-01-21 22:20:45
【问题描述】:
简介
我正在从我的数据库中获取消息(使用双向分页(最近的消息在底部,旧消息在顶部),所以每次我获取 15 条消息时,我都会将它们分成各自的日期组。
我有点卡住了,因为如果你想获得良好的性能,算法有点复杂......
代码
这是我当前的代码:
export default class MessagesDatesSectioner {
constructor(
dateOptions = {
weekday: "short",
year: "numeric",
month: "short",
day: "numeric",
}
) {
this.dateOptions = dateOptions;
this.sections = [];
this.sectionsRef = new Map();
}
/**
* Group a list of messages by date, generating a list of sections
* which contains a title (the messages day as string), and an array
* of data that contains all the messages.
*
* @param {list of objects} messages [{ date, text }, ...].
*/
sectionizeMessagesByDate(messages) {
let sections = messages.reduce((sections, message) => {
const key =
message.date
.toDate?.()
.toLocaleDateString(undefined, this.dateOptions) ||
message.date.toLocaleDateString(undefined, this.dateOptions);
if (!sections[key]) {
sections[key] = [];
}
sections[key].push(message);
return sections;
}, {});
sections = Object.keys(sections).map((key) => ({
title: key,
data: sections[key],
}));
// Merge the resulted sections with the existed ones
this.mergeNewMessagesSections(sections);
}
/**
* Get a list of new sections (or groups of messages), and merge them
* with the existing sections.
*
* @param {list of objects} newMessagesSections [{ title: "Monday", data: [{date, text}, ...], }, ...].
*/
mergeNewMessagesSections(newMessagesSections) {
for (const { title, data } of newMessagesSections) {
if (!this.sectionsRef.has(title)) {
this.sectionsRef.set(title, this.sections.length);
this.sections.push({ title, data: [] });
}
this.sections[this.sectionsRef.get(title)].data.push(...data);
}
}
deleteMessage(message) {
// TODO
}
// Return a copy of the sections list
getSections() {
return [...this.sections];
}
}
问题
我的问题是在向这些结构中添加数据时出现的。由于我使用的是双向分页,因此新消息的日期可能比以前分段的消息更早或更晚。
例如:
1- Call sectionizeMessagesByDate() with the following messages
[
{ date: new Date("10/31/2000 00:00:01"), text: "Hello" },
{ date: new Date("10/31/2001 00:00:02"), text: "World" },
] // Note: All messages are sorted by date in the given array by default (Do not care about it)
2- When merging, as there is no data in the sections list, it will generate the following:
[
{
title: "10/31/2000",
data: [ { date: new Date("10/31/2000 00:00:01"), text: "Hello" } ]
},
{
title: "10/31/2001", // Other year (different date)
data: [ { date: new Date("10/31/2000 00:00:02"), text: "Hello" } ]
}
]
如您所见,合并时新的部分会添加到当前部分列表的尾部...
因此,如果该类生成一个日期为“10/31/1999”的新部分,它将被添加到底部,而不是保留日期顺序。
任何想法如何实现节和节消息(在数据数组中)之间的排序(按日期)以保持良好的性能?
注意:map 'sectionsRef' 以节的标题为键,并在节列表中作为值进行索引,只是为了在将消息插入现有节时实现 O(1) 复杂度顺序。
【问题讨论】:
-
您通常会排序多少个项目?
-
@jarmod 此算法用于聊天屏幕(取决于用户滚动)。在每次滚动到达(或到达顶部,因为双向)时,用户从数据库中获得 15 条新消息(按日期排序)。这15条直接传给这个类(messagesDatesSectioner.sectionizeMessagesByDate(listOfMessages))。
标签: javascript algorithm performance optimization ecmascript-6