Skip to content

Instantly share code, notes, and snippets.

View hereisfun's full-sized avatar

calvinfung hereisfun

View GitHub Profile
@hereisfun
hereisfun / pubSub.js
Created March 7, 2017 13:54
简单的pub/sub模式实现
var pubSub = (function(){
//以各种event为键,值为该event绑定的callback队列
var eventQueues = {};
//此处只发布event本身,不携带其它信息。
//可稍作修改增加参数实现携带信息。
function pub(event){
if(!eventQueues[event]){
//若发布event时没有该event对应的callback队列
eventQueues[event] = [];
@hereisfun
hereisfun / timechunk.js
Last active March 13, 2017 12:31
分时函数,将一次性大批量的操作分割成多次小批量
//ary为要批量处理的数据,fn为对每个数据的操作方式,count为每次处理的量
var timechunk = function(ary, fn, count){
var obj,
timer;
var start = function(){
for(var i = 0; i < count; i++){
if(ary.length === 0){
return;
}
obj = ary.shift();
@hereisfun
hereisfun / throttle.js
Created March 13, 2017 12:55
节流函数,保证某一操作的最小时间间隔
//fn为要节流的操作,interval为最小操作间隔
var throttle = function(fn, interval){
var timer,
_fn = fn;//保存要延时的函数的引用
return function(){
var that = this;
var arg = arguments;
//如果有未完成的计时器,则不进行操作
@hereisfun
hereisfun / currying.js
Created March 13, 2017 13:38
函数柯里化
//将用于柯里化的函数本身最好能接受不定数量的参数
//此处的闭包是本意主要是让plus函数在不currying的情况下也能照常工作
var plus = (function(){
var result = 0;
return function(){
for(let i = 0; i < arguments.length; i++){
result += arguments[i];
}
return result;
}
@hereisfun
hereisfun / beforeAfter.js
Created March 14, 2017 12:09
装饰者模式
//用途1:组装新功能,不影响原函数
//用途2:动态改变参数。因为都用到了arguments指针,可通过arguments指针修改参数
//注意: 如果原本的函数带有属性,装饰后会丢失属性。因为返回的是一个新的函数。
var before = function(fn, beforefn){
return function(){
beforefn.apply(this, arguments);
return fn.apply(this, arguments);
}
@hereisfun
hereisfun / statusMode.js
Created March 14, 2017 12:49
状态模式
//状态模式
//重点在于状态机的切换逻辑,以及有相同的方法代理操作(如这里的btnpressed)
var STATUS = {
on: {
btnpressed: function(){
console.log('关灯了');
this.button.innerHTML = 'ON';
this.currentstatus = STATUS.off;
}
},
@hereisfun
hereisfun / quickSort.js
Last active March 15, 2017 07:48
传统原地快排,js实现
var arr = [];
for(let i = 0; i < 100; i++){
arr[i] = Math.round(Math.random()*99);
}
//上面是生成随机数组
function quickSort(arr){
function swap(arr, i, j){
@hereisfun
hereisfun / data-structures.js
Last active March 17, 2017 12:53
一些数据结构
//栈
function Stack(){
var value = [];
if(typeof this.isEmpty !== 'function'){
Stack.prototype.isEmpty = function(){
return value.length === 0;
}
}
@hereisfun
hereisfun / alg,js
Last active March 28, 2017 01:29
一些算法题
//Q:两个玻璃珠,n层楼,确定会摔碎的临界层所需的最少次数
//缓存递归过程中的结果
var cache = [];
function find(n) {
//确定递归的结束条件
if(n == 1){
return 1;
}
if(n == 0){
return 0;
@hereisfun
hereisfun / typeChecker.js
Created April 24, 2017 07:51
js类型检测,包括ES5/6
//从ES5.1开始,undefined和null能返回正确的[object Undefined] [object Null]
//且ES6多了更多类型,既然难易枚举完毕,干脆全都用Object.prototype.toString.call()
//基于ES5.1以下的
function type(data) {
// 对于null,typeof会返回object
if(data === null) {
return 'null';
}else if(data === undefined){
return 'undefined';