Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In a way, yes. On the other hand, it boils down the code that some poor soul of a maintenance programmer needs to deal with to a single line which is more readable, too. Win-Win.


I don't disagree. But then again I've had peers review code similar to this and flag an issue saying it's too clever because that poor soul might not know what "where" is doing or that the use of lambdas is "too complex."


That is certainly something I've also come across. This kind of functional style is very readable once you understand it, but it does have a learning curve just like learning what "for(var i = 0; i< length; i++)" means.

I actually did a little presentation to the team about how to refactor a for loop to an self implemented where/filter function to explain the connection. For me, realising that all the where was doing (or at least potentially, there might be some behind the scenes optimisations going on) was passing in the condition for an IF in a FOR loop suddenly clarified everything for me.

In case anyone's interested, this is these are the code steps (javascript)

  var people = [{name: 'bob', gender: 'male'}, {name: 'dave', gender: 'male'}, {name: 'sarah', gender: 'female'}];
  
  var getAllMen = function(population) {
      var returnList = [];
      for(var i = 0; i< population.length; i++){
          if(population[i].gender === 'male'){
              returnList.push(population[i]);
          }
      }
      return returnList;
  }
  
  var males = getAllMen(population);
  
  ___
  
  
  var getAllMen = function(population) {
      var returnList = [];
      for(var i = 0; i< population.length; i++){
          if(isMan(population[i]){
              returnList.push(population[i]);
          }
      }
      return returnList;
  }
  
  var isMan = function(person){
      return person.gender === 'male';
  }
  
  var males = getAllMen(population);
  
  ___
  
  var filter = function(anyOldList, filterCondition){
      var returnList = [];
      for(var i = 0; i< anyOldList.length; i++){
          if(filterCondition(anyOldList[i]){
              returnList.push(anyOldList[i]);
          }
      }
      return returnList;
  }
  
  var isMan = function(person){
      return person.gender === 'male';
  }
  
  var males = filter(population, isMan);
  
  var females = filter(population, function(person){
      person.gender === 'female';
  });
  
  
  var females = filter(population, person => person.gender === 'female');
  var females = filter(population, x => x.gender === 'female');




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: