-1

我需要根据他们的分数将一定数量的人分配给他们。规则是,他们的要求根据他们的立场得到满足,剩下的就是什么。在使用 Lo-Dash ( JSBin )的 JavaScript 中:

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}]

由于解决方案取决于顺序,是否可以更改此代码以使其成为纯功能?

4

1 回答 1

0

功能解决方案是折叠

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;
}
于 2014-07-27T10:07:01.067 回答