Skip to content

Instantly share code, notes, and snippets.

@zzuhan
Last active May 20, 2019 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzuhan/c456bf4c43810e901e6ee4d3830d0687 to your computer and use it in GitHub Desktop.
Save zzuhan/c456bf4c43810e901e6ee4d3830d0687 to your computer and use it in GitHub Desktop.
[interview] #js
Array.prototype._map = function(fn, bindThis) {
bindThis = bindThis || null;
return this.reduce(function(total, curr, currIndex, arr){
// console.log(total)
total.push(fn.call(bindThis, curr, currIndex, arr));
return total;
}, [])
};
Array.prototype._filter = function(fn, bindThis) {
bindThis = bindThis || null;
return this.reduce(function(total, curr, currIndex, arr){
if(fn.call(bindThis, curr, currIndex, arr)) {
total.push(curr);
}
return total;
}, [])
};
var arr = [1,3,4,2];
var ret = arr._map(function(item, index){
return item += 1;
});
var ret = arr._filter(function(item, index){
return item == 1;
});
console.log(ret);
// https://www.cnblogs.com/mackxu/archive/2013/03/24/inherit0.html inherit函数 代码更加严谨一点
function inherit(Child, Parent){
function f(){};
f.prototype = Parent.prototype;
Child.prototype = new f();
Child.constructor = Child;
}
// new的实现
// var object = {
// __proto__: F.prototype
// }
// F.bind(object, args);
function curry(fn, ...args1){
if(args1.length >= fn.length) {
return fn(...args1);
}
return function(...args2){
return curry(fn, ...args1, ...args2);
}
}
function add(x, y, z){
return x + y + z;
}
var addTen = curry(add, 10);
var addTweleve = addTen(2);
console.log(addTweleve(2));
function debounce(func, wait){
let timer = null;
return function(){
var context = this;
var args = [].slice.call(arguments, 0);
clearTimeout(timer);
timer = setTimeout(()=>{
func.apply(context, args);
}, wait);
}
}
let func = debounce((value)=>{
console.log(value);
}, 1000);
func(123);
func(1234);
String.prototype.trim = function(){
return this.replace(/(^\s+|\s+$)/g, '');
}
var string = ' 222121 22 1';
console.log(string.trim());
// 1 使用timer版本
// function throttle(func, wait){
// wait = wait || 0;
// var timer = null;
// var queue = [];
// return function(...args){
// var context = this;
// if(timer) return;
// let result = func.apply(context, args);
// timer = setTimeout(function(){
// timer = null;
// }, wait);
// return result;
// }
// }
// 2 采用记录时间版本
function throttle(func, wait){
wait = wait || 0;
var lastCallTime = 0;
var queue = [];
return function(...args){
var context = this;
if(lastCallTime + wait < Date.now()) {
lastCallTime = Date.now();
let result = func.apply(context, args);
return result;
}
}
}
// 3 队列中的函数仍然会执行,并有cancel函数的
var log = throttle((args)=>{
console.log(args)
}, 1000);
log(1);
setTimeout(()=>{
log(2);
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment