网易课题学习

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script src="lodash.js"></script>
  <script>
    // console.log(_.uniq([1,2,3,21,3,1,5,7,8,'a','A'],function(val) {
    //   return typeof val === 'string' ? val.toLocaleLowerCase() : val;
    // }))
    // console.log(_([1,2,3,21,3,1,5,7,8,'a','A']).uniq(function(val) {
    //   return typeof val === 'string' ? val.toLocaleLowerCase() : val;
    // }))

    console.log(_.chain([1,2,3,21,3,1,5,7,8]).uniq().reduce().value())
  </script>
</body>
</html>

lodash.js

(function(root){
  var _ = function(obj) {
    if(!(this instanceof _)) {
      return new _(obj);
    }
    this.wrap = obj;
  }

  _.reduce = function(obj) {
    var result = 0;
    for(var i=0; i<obj.length; i++) {
      result += obj[i]
    }
    return result;
  }

  // 数组去重
  _.uniq = function(target,callback) {
    var result = [];
    var computed;
    for(var i=0; i<target.length; i++) {
      computed = callback ? callback(target[i]) : target[i];
      if(result.indexOf(computed) === -1) {
        result.push(computed)
      }
    }
    return result;
  }

  // 开启连接式的调用
  _.chain = function(obj) {
    var instence  = _(obj);
    instence._chain = true;
    return instence;
  }

  // 终止连接式调用
  _.prototype.value = function() {
    return this.wrap;
  }

  // 辅助函数
  _.result = function(instence, obj) {
    return instence._chain ? _(obj).chain() : obj;
  }

  _.each = function(arr,callback) {
    for(var i=0; i<arr.length; i++) {
      callback.call(arr,arr[i])
    }
  }

  _.functions = function(obj) {
    var result = [];
    for(var key in obj) {
      result.push(key);
    }
    return result;
  }

  // 自身拓展的方法
  _.mixin  = function(obj) {
    _.each(_.functions(obj),function(key) {
      var func = obj[key];
      obj.prototype[key] = function() {
        var args = [this.wrap];
        args = args.concat(arguments[0])
        // args.push(arguments[0])
        // Array.prototype.push.apply(args,arguments)
        return _.result(this, func.apply(this, args));
      }      
    })
  }

  _.mixin(_);

  root._ = _;

})(this)
原文地址:https://www.cnblogs.com/kewenxin/p/10620345.html