如何在纯功能风格中分配数量
How to ration amount in purely functional style
我需要根据一组人的分数分配一定的金额。规则是,根据他们的立场,用剩下的任何东西满足他们的要求。在JavaScript中使用Lo-Dash (JSBin):
var amount = 1000,
people = [
{ name : 'Joe', score: 40, demand: 400},
{ name : 'Sue', score: 30, demand: 350},
{ name : 'Kim', score: 25, demand: 300},
{ name : 'Ron', score: 20, demand: 250}
];
function distribute(people, amount){
return _.map(_.sortBy(people,'need'),function(person){
var ration = Math.min(person.demand,amount);
amount -= ration; // This is the state (mutation) that I want to avoid
return _.assign(person,{ ration: ration})
});
}
console.log(distribute(people, amount));
结果:[{ demand: 400, name: "Joe", ration: 400, score: 40},
{ demand: 350, name: "Sue", ration: 350, score: 30},
{ demand: 300, name: "Kim", ration: 250, score: 25},
{ demand: 250, name: "Ron", ration: 0, score: 20}]
由于解决方案取决于顺序,是否有可能更改此代码以使其纯功能?
功能解决方案是折叠:
function distribute(people, amount) {
return _.foldl(_.sortBy(people, 'score'), function(result, person) {
var ration = Math.min(person.demand, result.remaining);
var resultPerson = _.assign(person, { ration: ration });
return { people: result.people.concat(resultPerson),
remaining: result.remaining - ration };
}, { people: [], remaining: amount }).people;
}
相关文章:
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- 在循环中分配json值时,值被覆盖
- 动态分配GA增强型电子商务跟踪器
- 将jsp文件下拉列表中的选定项分配给一个java变量(比如String selection)
- 为什么Airbnb风格指南说不鼓励依赖函数名称推断
- CKEditor-我在editor.css中的风格是't
- 如何在jQuery中将函数的输出分配给变量
- 为集合分配大量的模型弹药
- onclick函数需要双击,因为类分配延迟
- Javascript 将变量分配给警报
- 将节点数据分配给另一个变量jstree
- onclick风格的整个李不想要
- 如何发送分配列表<字符串>到JavaScript数组或可枚举对象
- Javascript变量分配-按类别
- 如何将内容分配给元素
- JavaScript改变了双方的显示风格
- 如何移除或改进:在Bootstrap Carousel上聚焦风格
- 为变量分配多个nodejs导出返回值时出现问题
- Jslint 错误:需要条件表达式,而是看到分配
- 如何在纯功能风格中分配数量