1 回答
TA贡献1772条经验 获得超6个赞
您的函数简单易读,只需删除大括号和return:
const usersActions = {
Bob: { eat: false, drink: false, sleep: true, walk: true },
Alice: { eat: true, drink: true, sleep: true, walk: false }
};
const Actions = {
Eat: 'eat',
Drink: 'drink',
Sleep: 'sleep',
Walk: 'walk'
}
const verifyActions = (name, actions) => actions.every((action) => usersActions[name][action]);
console.log(verifyActions('Bob', [Actions.Eat, Actions.Sleep])); // false
console.log(verifyActions('Bob', [Actions.Sleep, Actions.Walk])); // true
console.log(verifyActions('Alice', [Actions.Drink, Actions.Eat, Actions.Sleep])); // true
console.log(verifyActions('Alice', [Actions.Sleep, Actions.Walk])); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
使用 lodash,您可以从对象中选取所有操作userActions[name],然后检查是否所有操作都在true使用_.every(). 然而,这并没有使它更具可读性或更短。
const usersActions = {
Bob: { eat: false, drink: false, sleep: true, walk: true },
Alice: { eat: true, drink: true, sleep: true, walk: false }
};
const Actions = {
Eat: 'eat',
Drink: 'drink',
Sleep: 'sleep',
Walk: 'walk'
}
const verifyActions = (name, actions) => _.every(_.pick(usersActions[name], actions))
console.log(verifyActions('Bob', [Actions.Eat, Actions.Sleep])); // false
console.log(verifyActions('Bob', [Actions.Sleep, Actions.Walk])); // true
console.log(verifyActions('Alice', [Actions.Drink, Actions.Eat, Actions.Sleep])); // true
console.log(verifyActions('Alice', [Actions.Sleep, Actions.Walk])); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
添加回答
举报