var dragging = false;
var position = null;
xx.addEventLisenter('mousedown', e => {
dragging = true;
position = [e.clientX, e.clientY]
})
document.addEventLisenter('mousemove', e => {
if(!dragging) return;
const currX = e.clientX;
const currY = e.clientY;
const diffX = currX - position[0]
const diffY = currY - position[1]
const left = parseInt(xx.style.left || 0)
const top = parseInt(xx.style.top || 0)
xx.style.left = left + diffX + 'px'
xx.style.top = top + diffY + 'px'
position = [currX, currY]
})
document.addEventListener('mouseup', () => {
dragging = false;
})
function throttle(fn, delay) {
let flag = true,
timer = null;
return function (...args) {
const that = this;
if (!flag) return;
flag = false;
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(that, args);
flag = true;
}, delay);
}
}
function debounce(fn, delay) {
let timer = null
return function(...args) {
const that = this;
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(that, args)
}, delay)
}
}
var array = [1, 1, '1', '1', null, null,
undefined, undefined,
new String('1'), new String('1'),
/a/, /a/,
NaN, NaN
];
var unique1 = arr => [...new Set(arr)]
var unique2 = arr => arr.filter((item, index, arr) => arr.indexOf(item) === index)
var unique3 = arr => arr.reduce((pre, curr) => pre.includes(curr) ? pre : [...pre, curr], [])
let currying = (fn, ...args) =>
fn.length > args.length
? (...arguments) => currying(fn, ...args, ...arguments)
: fn(...args);
let addSum = (a, b, c) => a+b+c
let add = curry(addSum)
console.log(add(1)(2)(3))
console.log(add(1, 2)(3))
console.log(add(1,2,3))
function compose(...fn) {
if(!fn.length) return v => v;
if(fn.length === 1) return fn[0];
return fn.reduce((pre, curr) => (...args) => pre(curr(...args)))
}
function fn1(x) {
return x + 1;
}
function fn2(x) {
return x + 2;
}
function fn3(x) {
return x + 3;
}
function fn4(x) {
return x + 4;
}
const a1 = compose(fn1, fn2, fn3, fn4);
console.log(a1(1));
const flat = arr => {
return arr.reduce((pre, curr) => {
if(Array.isArray(curr)) {
return [...pre, ...flat(curr)]
} else {
return [...pre, curr]
}
}, [])
}
const flat1 = arr => arr.reduce((pre, curr) => pre.concat(Array.isArray(curr) ? flat(curr): curr), [])
const flat2 = (arr, deep = 1) =>
deep > 0
? arr.reduce((pre, curr) => pre.concat(Array.isArray(curr) ? flat(curr) : curr), [])
: arr.slice();
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
flat(arr1, Infinity);
function deepClone(obj, map = new WeakMap()) {
if (obj == null || typeof obj !== 'object') return obj;
if(map.has(obj)) {
return map.get(obj);
}
const constructor = obj.constructor;
if (/^(Date|RegExp)$/i.test(constructor.name)) {
return new constructor(obj);
}
const constructorObj = new constructor();
map.set(obj, constructorObj);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
constructorObj[key] = deepClone1(obj[key], map);
}
}
return constructorObj;
}
let obj = {
a: 1,
b: {
c: 2,
d: 3
},
d: new RegExp(/^\s+|\s$/g)
}
let clone_obj = deepClone1(obj)
obj.d = /^\s|[0-9]+$/g
console.log(clone_obj)
console.log(obj)
const isType = type => obj => Object.prototype.toString.call(obj) === `[object ${type}]`;
let isArray = isType('Array')
let isFunction = isType('Function')
console.log(isArray([1,2,3]),isFunction(Map))
Function.prototype.myCall = function(context, ...args) {
context = Object(context) || window;
const fn = Symbol()
context[fn] = this;
const res = context[fn](...args)
delete context[fn]
return res;
}
Function.prototype.myApply = function(context, args) {
context = Object(context) || window;
const fn = Symbol()
context[fn] = this;
const res = context[fn](...args);
delete context[fn]
return res;
}
let cc = {
a: 1
}
function demo(x1, x2) {
console.log(typeof this, this.a, this)
console.log(x1, x2)
}
demo.apply(cc, [2, 3])
demo.myApply(cc, [2, 3])
demo.call(cc,33,44)
demo.myCall(cc,33,44)
Function.prototype.myBind = function(context, ...args) {
return (...newArgs) => this.call(context, ...args, ...newArgs);
}
let cc1 = {
name : 'TianTian'
}
function say(something,other){
console.log(`I want to tell ${this.name} ${something}`);
console.log('This is some'+other)
}
let tmp = say.mybind(cc1,'happy','you are kute')
let tmp1 = say.bind(cc1,'happy','you are kute')
tmp()
tmp1()
function myNew(constructor, ...args) {
const obj = {};
obj.__proto__ = constructor.prototype;
const res = constructor.apply(obj, args)
if (res && typeof res === 'object' || typeof res === 'function') {
return res;
}
return obj;
}
function myInstanceof(left, right) {
if (left === null ||typeof left !== 'object') return false;
let proto = left.__proto__;
let prototype = right.prototype;
while(true) {
if (proto === null) return false;
if (proto === prototype) return true;
proto = proto.__proto__;
}
}
function sleep (fn, delay) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(fn)
}, delay);
})
}
let saySomething = (name) => console.log(`hello,${name}`)
async function autoPlay() {
let demo = await sleep(saySomething('TianTian'),1000)
let demo2 = await sleep(saySomething('李磊'),1000)
let demo3 = await sleep(saySomething('掘金的好友们'),1000)
}
autoPlay()
Array.prototype.myReduce = function(fn, initVal) {
let res = initVal,
i = 0;
if (typeof initVal === 'undefined') {
res = this[i];
i++;
}
while(i < this.length) {
res = fn(res, this[i]);
i++;
}
return res;
}
const arr = [3, 5, 1, 4, 2];
const a = arr.myReduce((t, v) => t + v);
function promiseResolve(val) {
if (val instanceof Promise) {
return val;
}
return new Promise(resolve => resolve(val))
}
function promiseReject(val) {
return new Promise((resolve, reject) => reject(val));
}
function promiseAll(arr) {
let index = 0, res = [];
return new Promise((resolve, reject) => {
arr.forEach((fn, i) => {
Promise.resolve(fn).then(data => {
index++;
res[i] = data;
if(index === arr.length) {
resolve(res);
}
}, err => {
reject(err);
})
});
})
}
function promiseRace(arr) {
return new Promise((resolve, reject) => {
arr.forEach(fn => {
Promise.resolve(fn).then(val => {
resolve(val)
}, err => reject(err))
})
})
}
function promiseAny() {}
function promiseAllSettLed() {}
function ajax({
url = '',
method = 'GET',
dataType = 'JSON',
async = true
}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(url, method, async);
xhr.responseType = dataType;
xhr.onreadystatechange = function() {
if(!/^[23]\d{2}$/.test(xhr.status)) return;
if (xhr.readyState === 4) {
resolve(xhr.responseText);
}
}
xhr.onerror = function (err) {
reject(err)
};
xhr.send();
})
}
function jsonp({url, params, callbackName}) {
const generateUrl = () => {
let dataSrc = '';
for(let key in params) {
if(params.hasOwnProperty(key)) {
dataSrc += `${key}=${params[key]}&`
}
}
dataSrc += `callback=${callbackName}`;
return `${url}?${dataSrc}`;
}
return new Promise((resolve, reject) => {
const el = document.createElement('script');
el.src = generateUrl();
document.body.appendChild(el);
window[callbackName] = function(data) {
resolve(data);
document.body.removeChild(el);
}
})
}
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function create(obj, props) {
function Fn() {}
Fn.prototype = obj;
Fn.prototype.constructor = Fn;
if(props) {
Object.defineProperties(obj, props);
}
return new Fn();
}
function convert(number, base = 2) {
let rem, res, digits = '0123456789ABCDEF', stack = [];
while(number) {
rem = number % base;
stack.push(rem);
number = Math.floor(number / base);
}
while(stack.length) {
res += digits[stack.pop()].toString();
}
return res;
}
function thoundth(num) {
let [int, faction] = String(num).split('.');
const intRes = int.replace(/(?=\B(\d{3})+$)/g, ',');
return `${intRes}.${faction}`;
}
function versionSort(arr) {
return arr.sort((a, b) => {
let i = 0;
const arr1 = a.split('.');
const arr2 = b.split('.');
while(true) {
const s1 = arr1[i];
const s2 = arr2[i];
i++;
if (s1 === undefined || s2 === undefined) {
return arr1.length - arr2.length;
}
if (s1 === s2) {
continue;
}
return s1 - s2;
}
})
}
function dom2Json(dom) {
let obj = {};
obj.tag = dom.tagName;
obj.children = [];
dom.childNodes.forEach(child => obj.children.push(dom2Json(child)));
return obj;
}
function _render (vnode) {
if (typeof vnode === 'number') {
vnode = String(vnode)
}
if (typeof vnode === 'string') {
return document.createTextNode(vnode);
}
const dom = document.createElement(vnode.tag);
if (vnode.attrs) {
Object.keys(vnode.attrs).forEach(key => {
dom.setAttribute(key, vnode.attrs[key]);
})
}
if (vnode.children) {
vnode.children.forEach(child => {
dom.appendChild(_render(child));
})
}
return dom;
}
function render(tem, data) {
return tem.replace(/\{\{(\w+)\}\}/g, (match, key) => {
return data[key];
})
}
function list2Tree (list) {
const temp = {};
const res = [];
list.forEach(item => {
temp[item.id] = item;
});
for(let i in temp) {
const curr = temp[i];
if (curr.parentId !== 0) {
if(!temp[curr.parentId].children) {
temp[curr.parentId].children = [];
}
temp[curr.parentId].children.push(curr);
} else {
res.push(temp[i]);
}
}
return res;
}
function tree2List(tree) {
const res = [];
function dfs (data) {
data.forEach(item => {
if(item.children) {
dfs(item.children)
delete item.children;
}
res.push(item);
})
}
dfs(tree);
return res;
}
const arrayLike = document.querySelectorAll('div')
const arrayLike1 = [...arrayLike]
Array.from(arrayLike)
Array.prototype.slice.call(arrayLike)
Array.apply(null, arrayLike)
Array.prototype.concat.apply([], arrayLike)
class EventEmitter {
constructor() {
this.events = {};
}
on(type, callback) {
if (!this.events[type]) {
this.events[type] = [];
}
this.event[type].push(callback);
}
emit(type, ...args) {
this.events[type]
&& this.events[type].forEach(fn => {
fn.call(this, ...args);
})
}
off(type, callback) {
if (this.events[type]) {
this.events[type] = this.events[type].filter(item => item !== callback)
}
}
once(type, callback) {
function fn(...args) {
callback(...args);
this.off(type, fn)
}
this.on(type, fn);
}
}
const event = new EventEmitter();
const handle = (...rest) => {
console.log(rest);
};
event.on("click", handle);
event.emit("click", 1, 2, 3, 4);
event.off("click", handle);
event.emit("click", 1, 2);
event.once("dbClick", () => {
console.log(123456);
});
event.emit("dbClick");
event.emit("dbClick");
function camelCase(str) {
return str.replace(/[-_\s]+(.)?/g, function(match, char) {
return char ? char.toUpperCase() : '';
})
}
function getUrlParams(url) {
let obj = {};
url.replace(/([^?&])=([^?&])/g, function(match, $1, $2) {
obj[$1] = $2;
});
return obj;
}
const sleep = time => new Promise(resolve => setTimeout(resolve, time));
const scheduler = new Scheduler(2);
const addTask = (time, val) => {
scheduler.add(() => {
return sleep(time).then(() => console.log(val));
});
};
addTask(1000, '1');
addTask(500, '2');
addTask(300, '3');
addTask(400, '4');
class Scheduler {
constructor(max) {
this.max = max;
this.count = 0;
this.queue = [];
}
add(fn) {
this.queue.push(fn);
this.runQueue();
}
runQueue() {
if (this.queue.length && this.count < this.max) {
const fn = this.queue.shift();
this.count += 1;
fn().then(() => {
this.count -= 1;
this.runQueue();
})
}
}
}
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.map = new Map();
}
get(key) {
if(this.map.has(key)) {
const temp = this.map.get(key);
this.map.delete(key);
this.map.set(key, temp);
return temp;
} else {
return -1;
}
}
put(key, value) {
if(this.map.has(key)) {
this.map.delete(key);
} else if (this.map.size >= this.capacity) {
this.map.delete(this.map.keys().next().value)
}
this.map.set(key, value);
}
}
let cache = new LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
console.log("cache.get(1)", cache.get(1))
cache.put(3, 3);
console.log("cache.get(2)", cache.get(2))
cache.put(4, 4);
console.log("cache.get(1)", cache.get(1))
console.log("cache.get(3)", cache.get(3))
console.log("cache.get(4)", cache.get(4))
setTimeout(() => {
const total = 100000;
const once = 20;
const loopCount = Math.ceil(total / once);
let countOfRender = 0;
const ul = document.querySelector('ul');
function add() {
const fragment = document.createDocumentFragment();
for(let i = 0; i < once; i++) {
const li = document.createElement('li');
li.innerText = Math.floor(Math.random() * total);
fragment.appendChild(li);
}
ul.appendChild(fragment);
countOfRender += 1;
loop();
}
function loop() {
if(countOfRender < loopCount) {
window.requestAnimationFrame(add);
}
}
loop();
}, 0)
setTimeout(() => {
const totle = 100000;
const once = 20;
const loopCount = Math.ceil(totle / once);
let renderCount = 0;
const ul = document.querySelector('ul');
function add() {
const fragment = document.createDocumentFragment();
for(let i = o; i< once; i++) {
const li = document.createElement('li');
li.innerhTMl = Math.floor(Math.random() * total);
fragment.appendChild(li);
}
ul.appendChild(fragment);
renderCount += 1;
loop();
}
function loop() {
if(renderCount < loopCount) {
window.requestAnimationFrame(add)
}
}
loop();
}, 0);