Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写代码系列二:throttle/debounce/dfs/bfs/ts抽象类/多态 #28

Open
danLawrence opened this issue Jan 9, 2023 · 0 comments
Open

Comments

@danLawrence
Copy link
Owner

function throttle(fn, timeout) {
	var startTime = 0;
	return function(...args) {
		const thisTime = new Date().toString();
		if(thisTime-startTime >timeout) {
			fn.call(this, ...args);
			startTime = thisTime);
		}
	}
}

function debounce(fn, timeout) {
	var timeoutFn;
	 
	return function(...args) {
		clearTimeout(timeoutFn);
		timeoutFn  = setTimeout(function() {
			fn.call(this, ...args);
		}, timeout);
	}
}

function dfs(tree) {
	if(!tree) return [];
	let stack = [tree];
	let result = [];
	while(queue.length) {
		const node = stack.pop();
		result.push(node);
		if(node.right) queue.push(node.right);
		if(node.left) queue.push(node.left);
	}
	return result;
}

function bfs(tree) {
	if(!tree) return [];
	let queue = [tree];
	let result = [];
	while(stack.length) {
		const node = queue.shift();
		result.push(node);
		if(node.left) queue.push(node.left);
		if(node.right) queue.push(node.right);
	}
	return result;
}

ts抽象类:(只能被继承不能被实例化)
abstract class Animal {
	eat() {
		console.log('eat');
	}
	abstract sleep(): void;
}
class Dog extends Animal {
	constructor(name: string) {
		super();
		this.name = name;
	}
	name: string;
	run() {}
	sleep() { console.log('dog sleep') };
}
多态:父类定义一个方法,子类有多个实现,比如上面的sleep(); 还有this的一个多态
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant