随手记一个漂亮的code

代码

从前有个代码长这样

if (a) {
  if (b) {
    c
  }
} else {
  if (d) {
    c
  }
}

后来长这样

if (a && b  || !a && d) {
    c
}

再后来长这样。

if (a? b : d) {
    c
}

every 解决foreach中的return

有时候,我们需要从数组中筛选一些东西,filter当然可以,但是有些定制化的东西就很难,而且,在foreach中不能return。every 解决foreach中的return

array.every( item => {
    if (...){
        // some code
        return false
    } else {
        return true
    }
})

用!~代替 === -1

不过可能不容易看懂

!~ -1 // true

!~[1].indexof(1) // false

常用code utils

函数节流

2次执行间隔为x ms

var tr = function (time, fn) {
    this.fn = fn;
    this.time = time
    this.buffer = [];
    this._lastTriggerTime = 0;
}
tr.prototype._flushIfNeeded = function() {
    var start = Date.now();
    if ( this.buffer.length <=0 || start - this._lastTriggerTime <= this.time) {
        return;
    }
     
    this.fn(this.buffer.pop());
    this.buffer = [];
    this._lastTriggerTime = Date.now();
    
    setTimeout(this._flushIfNeeded.bind(this), this.time);
}
tr.prototype.trigger =function (arr) {
    this.buffer.push(arr);
    this._flushIfNeeded();
}
var nf = new tr(1000, function(arr){
    console.log(arr);
});
nf.trigger('hallo');
nf.trigger('hallo');
nf.trigger('hallo');

deepClone

function deepClone(obj){
  var res=Array.isArray(obj)?[]:{};
  for(var key in obj){
    if (typeof obj[key]=="object") {
      res[key]=deepClone(obj[key]);
    }else{
      res[key]=obj[key];
    }
  }
  return res;
}

Function.prototype.bind shim

function bind (context) {
  var target = this
  var bindArgs = Array.prototype.slice.call(arguments, 1)

  function bound () {
    var callArgs = Array.prototype.slice.call(arguments)
    if (this instanceof bound) { // 判断bind后的函数是不是通过new来调用的。如果是就指向自己,不然就指向context
      return target.apply(this, callArgs.concat(bindArgs))
    } else {
      return target.apply(context, callArgs.concat(bindArgs))
    }
  }

  // 实现继承,让bound函数生成的实例通过原型链能追溯到target函数
  // 即 实例可以获取/调用target.prototype上的属性/方法
  var Empty = function () {}
  Empty.prototype = target.prototype
  bound.prototype = new Empty()  // 这里如果不加入Empty,直接bound.prototype = target.prototype的话.改变bound.prototype则会影响到target.prototype,原型继承基本都会加入这么一个中间对象做屏障
   bound.prototype.constructor = bound;  //  constructor修正,防止调用constructor函数出错

  return bound
}

用fixup 和autosquash让git commit 更清楚

某个正常的提交

git add . 
git commit -m "feature A"
git log --graph --pretty=oneline --abbrev-commit

如果我的feature A有bug可以这样操作:

git add .
git commit --fixup 8831bd1 -> feature A的id

然后用autosquash合并两个commit

git rebase -i --autosquash 4dd17ad -> feature A的前一个id

git会自动帮你找出fixup的提交,和正常提交合并,你只需要在vim里面直接保存就可以了。

posted @ 2018-03-25 18:26  chenby  阅读(302)  评论(0编辑  收藏  举报