gpt4 book ai didi

javascript - 不可变的 js : make a function more. 。功能性的

转载 作者:行者123 更新时间:2023-11-30 12:06:45 24 4
gpt4 key购买 nike

我有一个在 Immutable.js 上运行的 reducer 函数记录,一个日历:

const Calendar = new Record({
'events': new List(), // list of Events
});

这是 Event 的列表:

const Event = new Record({
'start': null,
'end': null,
'title': null,
});

我想将来自 Javascript 对象的新事件添加到此列表并返回一个新的 Calendar 记录,但前提是对象不在列表中:

(state = new Calendar)=> {

const receivedEvent = new Event({
start: <a date>,
end: <another date>,
title: <a string>,
});

let newState;

if (state.get('events').contains(receivedEvent)){
newState = state;
} else {
newState = state
.updateIn(['events'], (events)=> events.push(receivedEvent));
}

return newState;
}

这是我现在凌晨 4 点能做的最好的事情,但这似乎是一个糟糕的方法。

有没有办法更好地利用功能范例(例如 Immutable 提供的范例)来完成同样的任务?

最佳答案

如果您正在处理一个成员资格很重要的集合,那么您可能想要使用 Set不是列表。

集合只是唯一值的集合。

const Calendar = new Record({
'events': new Set(), // set of Events
});

然后您可以将事件添加到集合中,而不必担心最终会出现重复值。数据结构的实现使您不必检查它是否已经包含该值。

(state = new Calendar) =>
state.updateIn(['events'], calendar => calendar.add(new Event({
start: <a date>,
end: <another date>,
title: <a string>,
}));

当您表示日历时,添加事件的顺序可能并不重要,因为您可以使用事件日期本身作为列表进行排序,否则,您可以使用 OrderedSet以保留顺序。

关于javascript - 不可变的 js : make a function more. 。功能性的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34991809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com