Function.prototype.call2 = function (context) {
var context = Object(context) || window;
context.fn = this;
var params = [];
for (var i = 1; i < arguments.length; i++) {
params.push("arguments[" + i + "]");
}
var result = eval("context.fn(" + params + ")");
delete context.fn;
return result;
};
Function.prototype.apply2 = function (context, arr) {
var context = Object(context) || window;
context.fn = this;
var result;
if (!arr) {
result = context.fn();
} else {
var params = [];
for (var i = 0; i < arr.length; i++) {
params.push("arr[" + i + "]");
}
result = eval("context.fn(" + params + ")");
}
delete context.fn;
return result;
};
Function.prototype.bind2 = function (context) {
var self = this;
var args = Array.prototype.slice.call2(arguments, 1);
var fn = function () {
var bindArgs = args.concat(Array.prototype.slice.call2(arguments));
return self.apply2(this instanceof fn ? this : context, bindArgs);
};
var fNOP = function () {};
fNOP.prototype = this.prototype;
fn.prototype = new fNOP();
return fn;
};
function objectFactory() {
var obj = {};
var Constructor = Array.prototype.shift.call2(arguments);
obj.__proto__ = Constructor.prototype;
var result = Constructor.apply2(obj, arguments);
return typeof result === "object" ? result : obj;
}
function createPerson(name) {
var o = new Object();
o.name = name;
o.getName = function () {
console.log(this.name);
};
return o;
}
var person1 = createPerson("kevin");
function Person(name) {
this.name = name;
this.getName = getName;
}
function getName() {
console.log(this.name);
}
var person1 = new Person("kevin");
function Person(name) {}
Person.prototype = {
constructor: Person,
name: "kevin",
getName: function () {
console.log(this.name);
},
};
var person1 = new Person();
function Person(name) {
this.name = name;
}
Person.prototype = {
constructor: Person,
getName: function () {
console.log(this.name);
},
};
var person1 = new Person();
function Person(name) {
this.name = name;
if (typeof this.getName != "function") {
Person.prototype.getName = function () {
console.log(this.name);
};
}
}
var person1 = new Person();
function Person(name) {
var o = new Object();
o.name = name;
o.getName = function () {
console.log(this.name);
};
return o;
}
var person1 = new Person("kevin");
console.log(person1 instanceof Person);
console.log(person1 instanceof Object);
function person(name) {
var o = new Object();
o.sayName = function () {
console.log(name);
};
return o;
}
var person1 = person("kevin");
person1.sayName();
person1.name = "daisy";
person1.sayName();
console.log(person1.name);
function Parent() {
this.name = "kevin";
}
Parent.prototype.getName = function () {
console.log(this.name);
};
function Child() {}
Child.prototype = new Parent();
var child1 = new Child();
console.log(child1.getName());
function Parent() {
this.names = ["kevin", "daisy"];
}
function Child() {
Parent.call(this);
}
var child1 = new Child();
child1.names.push("yayu");
console.log(child1.names);
var child2 = new Child();
console.log(child2.names);
function Parent(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
Parent.prototype.getName = function () {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child1 = new Child("kevin", "18");
child1.colors.push("black");
console.log(child1.name);
console.log(child1.age);
console.log(child1.colors);
var child2 = new Child("daisy", "20");
console.log(child2.name);
console.log(child2.age);
console.log(child2.colors);
function createObj(o) {
function F() {}
F.prototype = o;
return new F();
}
var person = {
name: "kevin",
friends: ["daisy", "kelly"],
};
var person1 = createObj(person);
var person2 = createObj(person);
person1.name = "person1";
console.log(person2.name);
person1.__proto__.name = "person1";
console.log(person2.name);
person1.friends.push("taylor");
console.log(person2.friends);
function createObj(o) {
var clone = Object.create(o);
clone.sayName = function () {
console.log("hi");
};
return clone;
}
function Parent(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
Parent.prototype.getName = function () {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
var child1 = new Child("kevin", "18");
console.log(child1);
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
function prototype(child, parent) {
var prototype = object(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
prototype(Child, Parent);
function debounce(func, wait, immediate) {
var timeout, result;
var debounced = function () {
var context = this;
var args = arguments;
if (timeout) {
clearTimeout(timeout);
}
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(function () {
timeout = null;
}, wait);
if (callNow) {
result = func.apply(context, args);
}
} else {
timeout = setTimeout(function () {
func.apply(context, args);
}, wait);
}
return result;
};
debounced.cancel = function () {
clearTimeout(timeout);
timeout = null;
};
return debounced;
}
function throttle(func, wait) {
var prev = 0;
return function () {
var now = Date.now();
var context = this;
var args = arguments;
if (now - prev > wait) {
func.apply(context, args);
prev = now;
}
};
}
function throttle(func, wait) {
var timeout;
return function () {
var context = this;
var args = arguments;
if (!timeout) {
timeout = setTimeout(function () {
func.apply(context, args);
timeout = null;
}, wait);
}
};
}
function throttle(func, wait) {
var timeout, context, args;
var prev = 0;
var throttled = function () {
context = this;
args = arguments;
var now = Date.now();
var remain = wait - (now - prev);
if (remain <= 0 || remain > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
func.apply(context, args);
prev = now;
} else if (!timeout) {
timeout = setTimeout(function () {
prev = Date.now();
timeout = null;
func.apply(context, args);
}, remain);
}
};
return throttled;
}
var array = [1, 1, "1"];
function unique(array) {
var res = [];
var sortedArray = array.concat().sort();
var seen;
for (var i = 0, len = sortedArray.length; i < len; i++) {
if (!i || seen !== sortedArray[i]) {
res.push(sortedArray[i]);
}
seen = sortedArray[i];
}
return res;
}
var array = [1, 2, 1, 1, "1"];
function unique(array) {
var res = array.filter(function (item, index, array) {
return array.indexOf(item) === index;
});
return res;
}
console.log(unique(array));
var array = [1, 2, 1, 1, "1"];
function unique(array) {
return array
.concat()
.sort()
.filter(function (item, index, array) {
return !index || item !== array[index - 1];
});
}
console.log(unique(array));
var unique = (a) => [...new Set(a)];
function type(obj) {
var class2type = {};
"Boolean Number String Function Array Date RegExp Object Error"
.split(" ")
.map(function (item, index) {
class2type["[object " + item + "]"] = item.toLowerCase();
});
if (obj == null) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function"
? class2type[Object.prototype.toString.call(obj)] || "object"
: typeof obj;
}
function isPlainObject(obj) {
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var proto, Ctor;
if (!obj || toString.call(obj) !== "[object Object]") {
return false;
}
proto = Object.getPrototypeOf(obj);
if (!proto) {
return true;
}
Ctor = hasOwn.call(proto, "constructor") && proto.constructor;
return (
typeof Ctor === "function" &&
hasOwn.toString.call(Ctor) === hasOwn.toString.call(Object)
);
}
function isEmptyObject(obj) {
var name;
for (name in obj) {
return false;
}
return true;
}
function isWindow(obj) {
return obj != null && obj === obj.window;
}
function isArrayLike(obj) {
var length = !!obj && "length" in obj && obj.length;
var typeRes = type(obj);
if (typeRes === "function" || isWindow(obj)) {
return false;
}
return (
typeRes === "array" ||
length === 0 ||
(typeof length === "number" && length > 0 && length - 1 in obj)
);
}
function isElement(obj) {
return !!(obj && obj.nodeType === 1);
}
function shallowCopy(obj) {
if (typeof obj !== "object") {
return;
}
var newObj = obj instanceof Array ? [] : {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = obj[key];
}
}
return newObj;
}
function deepCopy(obj) {
if (typeof obj !== "object") {
return;
}
var newObj = obj instanceof Array ? [] : {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] =
typeof obj[key] === "object" ? deepCopy(obj[key]) : obj[key];
}
}
return newObj;
}
var arr = [6, 4, 1, 8, 2, 11, 23];
var max = eval("Math.max(" + arr + ")");
console.log(max);
var arr = [6, 4, 1, 8, 2, 11, 23];
console.log(Math.max.apply(null, arr));
var arr = [6, 4, 1, 8, 2, 11, 23];
console.log(Math.max(...arr));
var arr = [1, [2, [3, 4]]];
function flatten(arr) {
var result = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
console.log(flatten(arr));
var arr = [1, [2, [3, 4]]];
function flatten(arr) {
return arr.reduce(function (prev, next) {
return prev.concat(Array.isArray(next) ? flatten(next) : next);
}, []);
}
console.log(flatten(arr));
var arr = [1, [2, [3, 4]]];
function flatten(arr) {
while (arr.some((item) => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
console.log(flatten(arr));
function flatten(input, shallow, strict, output) {
output = output || [];
var idx = output.length;
for (var i = 0, len = input.length; i < len; i++) {
var value = input[i];
if (Array.isArray(value)) {
if (shallow) {
var j = 0,
length = value.length;
while (j < length) output[idx++] = value[j++];
}
else {
flatten(value, shallow, strict, output);
idx = output.length;
}
}
else if (!strict) {
output[idx++] = value;
}
}
return output;
}
var partial = function (fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
var newArgs = args.concat(Array.prototype.slice.call(arguments));
return fn.apply(this, newArgs);
}
}
function add(a, b) {
return a + b;
}
var addCurry = partial(add, 1, 2);
addCurry()
var addCurry = partial(add, 1);
addCurry(2)
var addCurry = partial(add);
addCurry(1, 2)
function curry(fn, args) {
var length = fn.length;
args = args || [];
return function () {
var newArgs = args.slice().concat(Array.prototype.slice.call(arguments));
if (newArgs.length < length) {
return curry.call(this, fn, newArgs);
} else {
return fn.apply(this, newArgs);
}
}
}
var fn = curry(function(a, b, c) {
return [a, b, c];
});
fn("a")("b", "c")
function addEvent(type, el, fn) {
if (window.addEventListener) {
addEvent = function(type, el, fn) {
el.addEventListener(type, fn, false);
}
}
else if (window.attachEvent) {
addEvent = function(type, el, fn) {
el.attachEvent('on' + type, fn);
}
}
}
var addEvent = (function(){
if (window.addEventListener) {
return function (type, el, fn) {
el.addEventListener(type, fn, false);
}
}
else if(window.attachEvent){
return function (type, el, fn) {
el.attachEvent('on' + type, fn);
}
}
})();
var toUpperCase = function(x) { return x.toUpperCase(); };
var hello = function(x) { return 'HELLO, ' + x; };
function compose() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[i].apply(this, arguments);
while(i--) {
result = args[i].call(this, result);
}
return result;
}
}
var greet = compose(hello, toUpperCase);
greet('kevin');
function pipe() {
var args = arguments;
return function() {
var i = 0;
var result = args[i].apply(this, arguments);
i++;
while(i < args.length) {
result = args[i].call(this, result);
i++;
}
return result;
}
}
var greet = pipe(toUpperCase, hello);
greet('kevin');
var add = function(a, b, c) {
return a + b + c
}
var memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = '' + (hasher ? hasher.apply(this, arguments) : key);
if (!cache[address]) {
cache[address] = func.apply(this, arguments);
}
return cache[address];
}
memoize.cache = {};
return memoize;
};
var memoizedAdd = memoize(add, function(){
var args = Array.prototype.slice.call(arguments)
return JSON.stringify(args)
})
console.log(memoizedAdd(1, 2, 3))
console.log(memoizedAdd(1, 2, 4))
function Promise2(fn) {
this.cbs = [];
const resolve = (value) => {
setTimeout(() => {
this.data = value;
this.cbs.forEach((cb) => cb(value));
})
};
fn(resolve);
}
Promise2.prototype.then = function(onResolved) {
return new Promise2((resolve) => {
this.cbs.push(() => {
const result = onResolved(this.data);
if (result instanceof Promise2) {
result.then(resolve);
} else {
resolve(result);
}
})
});
}
new Promise2((resolve) => {
setTimeout(() => {
resolve(1);
}, 500);
})
.then((res) => {
console.log(res);
return new Promise2((resolve) => {
setTimeout(() => {
resolve(2);
}, 500);
});
})
.then(console.log);
function compose(...funcs) {
return funcs.reduce((a, b) => (...args) => a(b(...args)));
}
function createStore(reducer, middlewares) {
let currentState;
function dispatch(action) {
currentState = reducer(currentState, action);
}
function getState() {
return currentState;
}
dispatch({
type: "INIT"
});
let enhancedDispatch = dispatch;
if (middlewares) {
enhancedDispatch = compose(...middlewares)(dispatch);
}
return {
dispatch: enhancedDispatch,
getState
};
}
const otherDummyMiddleware = dispatch => {
return action => {
console.log(`type in dummy is ${type}`);
return dispatch(action);
};
};
const typeLogMiddleware = dispatch => {
return ({ type, ...args }) => {
console.log(`type is ${type}`);
return dispatch({ type, ...args });
};
};
const counterStore = createStore(counterReducer, [
typeLogMiddleware,
otherDummyMiddleware
]);
console.log(counterStore.getState().count);
counterStore.dispatch({ type: "add", payload: 2 });
console.log(counterStore.getState().count);
class Koa {
constructor() {
this.middlewares = [];
}
use(middleware) {
this.middlewares.push(middleware);
}
start({ req }) {
function composeMiddlewares(middlewares) {
return function wrapMiddlewares(ctx) {
let index = -1;
function dispatch(i) {
index = i;
const fn = middlewares[i];
if (!fn) {
return Promise.resolve();
}
return Promise.resolve(
fn(
ctx,
() => dispatch(i + 1)
)
);
}
return dispatch(0);
};
}
const composed = composeMiddlewares(this.middlewares);
const ctx = { req, res: undefined };
return composed(ctx);
}
}
app.use(async (ctx, next) => {
try {
await next();
} catch (error) {
console.log(`[koa error]: ${error.message}`);
}
});
app.use(async (ctx, next) => {
const { req } = ctx;
console.log(`req is ${JSON.stringify(req)}`);
await next();
console.log(`res is ${JSON.stringify(ctx.res)}`);
});
app.use(async (ctx, next) => {
const { req } = ctx;
console.log(`calculating the res of ${req}...`);
const res = {
code: 200,
result: `req ${req} success`
};
ctx.res = res;
await next();
});
app.start({ req: "ssh" });