/*
  function(args) {
  fn.apply(this, args);
  }.bind(this, arguments)
  is
  Function.prototype.apply.bind(fn, this, arguments);
*/

// uses timeout:
// execute func after timeout if no interuption
// events have 'old' timeStamp

var errorText =
  'Debounce function needs at least two arguments: ' +
  'function and delay. Number of passed arguments: ';

// ES5 all the way
module.exports = function debounce(fn, delay) {
  var timer = null;
  if (arguments.length < 2)
    throw new Error(errorText + arguments.length);
  var additionalArgs = Array.prototype.slice.call(arguments, 2);
  return function debounced() {
    var args = Array.prototype.slice.call(arguments);
    if (additionalArgs.length)
      Array.prototype.push.apply(args, additionalArgs);
    args.push(this);
    clearTimeout(timer);
    timer = setTimeout(Function.prototype.apply.bind(fn, this, args), delay);
  };
};

// document.addEventListener('click', debounce((...b) => { console.log(b); }, 500, 1, 2, 3));
// -> [MouseEvent, 1, 2, 3, document]
// document.addEventListener('click', debounce((...b) => { console.log(b); }, 500));
// -> [MouseEvent, document]
