underscore functions
for study
by aniketmhatre88
Babel + JSX
let _ = {
bind(func, obj, ...args) {
return function() {
return func.call(obj, ...args);
};
},
bindAll(obj, ...methodNames) {
for(let i=0; i< methodNames.length; i++) {
let funcName = methodNames[i],
func = obj[funcName];
obj[funcName] = function(...args){
return func.call(obj, ...args);
};
}
},
memoize(func, hashFunc) {
let cache = {};
return function(...args) {
let key = hashFunc? hashFunc.call(this, ...args) : args,
cachedVal = cache[key];
if(cachedVal) {
return cachedVal;
}
let result = func.call(this, ...args);
cache[key] = result;
return result;
};
},
delay(func, wait, ...args) {
setTimeout(function() {
func.call(this, ...args);
}, wait);
},
defer(func, args) {
setTimeout(function() {
func.call(this, ...args);
}, 0);
},
debounce(func, wait, immediate) {
let timeout;
return function() {
let context = this,
args = arguments;
let later = function() {
timeout = null;
if(!immediate) {
func.apply(context, args);
}
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait || 200);
if(callNow) {
func.apply(context, args);
}
}
},
throttle(func, wait, trailing) {
let timeout;
return function() {
if (!timeout) {
let context = this,
args = arguments;
let funcToRun = function() {
timeout = null;
if (trailing) {
func.apply(context, args);
}
}
timeout = setTimeout(funcToRun, wait || 200);
if (!trailing) {
func.apply(context, args);
}
}
};
},
once(func) {
let cached;
return function() {
if...