gpt4 book ai didi

javascript - 这不是纯函数吗?

转载 作者:行者123 更新时间:2023-12-01 01:00:14 27 4
gpt4 key购买 nike

我正在学习 Web 开发的状态管理,并遇到了这个带有纯函数的 redux 教程,如下所示。然而声明: “action.todo.id = state.todos.length + 1;”让我怀疑这个纯函数是……不纯的。请赐教,谢谢!

export function rootReducer(state: IAppState, action): IAppState {

switch (action.type) {
case ADD_TODO:
action.todo.id = state.todos.length + 1;
return Object.assign({}, state, {
todos: state.todos.concat(Object.assign({}, action.todo)),
lastUpdate: new Date()
})

case TOGGLE_TODO:
var todo = state.todos.find(t => t.id === action.id);
var index = state.todos.indexOf(todo);
return Object.assign({}, state, {
todos: [
...state.todos.slice(0, index),
Object.assign({}, todo, {isCompleted: !todo.isCompleted}),
...state.todos.slice(index+1)
],
lastUpdate: new Date()
})
case REMOVE_TODO:
return Object.assign({}, state, {
todos: state.todos.filter(t => t.id !== action.id),
lastUpdate: new Date()
})
case REMOVE_ALL_TODOS:
return Object.assign({}, state, {
todos: [],
lastUpdate: new Date()
})
}
return state;
}

最佳答案

TL;DR - 不,不是。

让我们检查一下纯函数的定义。来自维基百科:

In computer programming, a pure function is a function that has thefollowing properties:

  1. Its return value is the same for the same arguments (no variation withlocal static variables, non-local variables, mutable referencearguments or input streams from I/O devices).

  2. Its evaluation has noside effects (no mutation of local static variables, non-localvariables, mutable reference arguments or I/O streams).

尽管您的函数确实符合第二个条件,但使用 new Date() - 使其变得不纯。

在您的情况下其不纯的原因是每个函数调用的日期都不同 - 无论传递的参数如何。

为了使其纯粹,您应该将日期作为附加参数传递,这将允许您为相同的输入获得相同的输出。

Zaptree 还提到,改变项目 ID 的长度,即 action.todo.id = state.todos.length + 1 是不纯粹的,因为它可能会影响引用它的其他方。

关于javascript - 这不是纯函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56150159/

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