Skip to content

Instantly share code, notes, and snippets.

View lushijie's full-sized avatar

Shijie Lu lushijie

  • Meituan && Qihoo 360
  • Beijing
View GitHub Profile
@lushijie
lushijie / enclosure.js
Last active February 12, 2024 00:02
通用javascript模块化封装
;(function() {
function MyModule() {
// ...
}
var moduleName = MyModule;
if (typeof module !== 'undefined' && typeof exports === 'object' && define.cmd) {
module.exports = moduleName;
} else if (typeof define === 'function' && define.amd === 'object' && define.amd) {
define(function() {
@lushijie
lushijie / truthy.js
Last active February 18, 2016 02:13
判断值是否存在&&是否为真
//undefined 与 null 返回false,其他返回true
function existy(x) {
return x != null;
}
function truthy(x) {
return (x !== false) && existy(x);
}
function doWhen(condtion, action) {
@lushijie
lushijie / curry.js
Last active February 18, 2016 02:17
函数柯里化
function Foo(x, y, z, w) {
var args = arguments;
if (args.length < Foo.length) {
return function() {
var oldArgs = Array.prototype.slice.call(args);
var newArgs = oldArgs.concat(Array.prototype.slice.call(arguments));
return args.callee.apply(null,newArgs);
}
} else {
return x + y - z * w;
@lushijie
lushijie / reduce.js
Last active February 18, 2016 02:18
数组reduce方法
//1.数组求和
var arr = [1,2,3,4];
var total = arr.reduce(function(pre, cur, index, arr){
//接受四个参数:初始值(或者上一次回调函数的返回值),当前元素值,当前索引,调用 reduce 的数组
//arr.reduce(callback,[initialValue])
return pre + cur;
})
console.log(total)
//2.把二维数组转换为json键值对
var relArray = [
@lushijie
lushijie / onceWraper.js
Last active February 18, 2016 02:30
函数一次运行包装器
function onceWraper(func){
return function(){
if(func){
var ret = func.apply(this,arguments);
func = null;
return ret;
}else{
console.log('非第一次运行不再执行');
return;
}
@lushijie
lushijie / shareFunc.js
Created February 18, 2016 03:09
程序多次运行共享一个状态
function shareFunc(func){
//初始化函数运行过程中依赖的变量
//之前一般的方式是声明全局变量,程序的阅读与理解难度增加,全局变量容易受干扰
var varWraper ={
a:0
}
return function(){
var args = [].slice.apply(arguments);
args.push(varWraper);
var ret = func.apply(this,args);
$.debounce = function(fn, time, ctx) {
var ret = 0;
if( typeof time !== 'number' ) {
ctx = time;
time = 50;
}
time = time || 50;
return function() {
var args = [].slice.apply(arguments);
// 注意是ctx的问题
@lushijie
lushijie / Analytics.js
Created February 23, 2016 07:18
代码引入
(function(i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function() {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
@lushijie
lushijie / declareAndCall.js
Created June 2, 2016 01:23
函数定义并立即执行
var func = (function f(a) {
console.log(a);
return f;
})('Hello World');
@lushijie
lushijie / shortFunctionCall.js
Created June 2, 2016 01:35
简短版函数调用
function x() {
console.log('x')
};
function y() {
console.log('y')
};
var z = 3;
(z==3?x:y)();