作家
登录

如何写出小而清晰的函数?(JS 版)

作者: 来源: 2017-08-11 14:47:32 阅读 我要评论

  •   const WEIGHT_OBJECT_FUNCTION = 4; 
  •  
  •   if (value == null) { 
  •  
  •     return WEIGHT_NULL_UNDEFINED; 
  •  
  •   } 
  •  
  •   if (typeof value === 'object' || typeof value === 'function') { 
  •  
  •     return WEIGHT_OBJECT_FUNCTION; 
  •  
  •   } 
  •  
  •   return WEIGHT_PRIMITIVE; 
  •  
  •  
  • // Code extracted into getMapValues() 
  •  
  • function getMapValues(map) {   
  •  
  •   return [...map.values()]; 
  •  
  •  
  • // Code extracted into getPlainObjectValues() 
  •  
  • function getPlainObjectValues(object) {   
  •  
  •   return Object.keys(object).map(function (key) { 
  •  
  •     return object[key]; 
  •  
  •   }); 
  •  
  •  
  • function getCollectionWeight(collection) {   
  •  
  •   let collectionValues; 
  •  
  •   if (collection instanceof Array) { 
  •  
  •     collectionValues = collection; 
  •  
  •   } else if (collection instanceof Map) { 
  •  
  •     collectionValues = getMapValues(collection); 
  •  
  •   } else { 
  •  
  •     collectionValues = getPlainObjectValues(collection); 
  •  
  •   } 
  •  
  •   return collectionValues.reduce(function(sum, item) { 
  •  
  •     return sum + getWeightByType(item); 
  •  
  •   }, 0); 
  •  
  •  
  • let myArray = [null, { }, 15];   

      推荐阅读

      安全36计 你需要了解的那些安全术语

    【51CTO.com快译】 软件开辟中的安然主题是多种多样的,安然术语对不合的团队具有不合的含义。为赞助澄清问题和避免安然问题的混淆,小编列出了A-Z最重要的安然相干词条供你参考。 A>>>详细阅读


    本文标题:如何写出小而清晰的函数?(JS 版)

    地址:http://www.17bianji.com/lsqh/36650.html

  • 关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)