[Javascript] lodash: memoize() to improve the profermence

Link: https://lodash.com/docs#memoize

 

Example: 

.service('UserPresenter', function(UserConstants){
  var typeFromId = _.memoize(function(typeId){
    var obj = _.findWhere(UserConstants.types, { value: typeId});
    return obj ? obj.display : '';    
  });
  
  return {
    fullName: function(user){
      return user.firstName + ' ' + user.lastName;
    },
    type: function(user){
      return typeFromId(user.typeId);
    }
  };
})

 

It is useful when you want to find something like userId, then you can use memoize() to cache the result.

 

posted @ 2016-03-16 15:15  Zhentiw  阅读(338)  评论(0编辑  收藏  举报