组件是指Web页面上抽出来的一个个包含模块(HTML)、样式(CSS)和功能(JS)的单元。好的组件具备封装性、正确性、扩展性、复用性。实现组件的步骤:结构设计、展现效果、行为设计,三次重构:插件化重构、模板化重构、抽象化重构。
过程抽象是指用来处理局部细节控制的一些方法,是函数式编程思想的基础应用。
//零阶高阶函数,等价于直接调用函数
function HOF_0 (fn){
return function(...args){
return fn.apply(this.args);
}
}
function once ( fn ) {
return function (...args){
const res = fn.allpy (this.args);
fn = null;
return res;
}
}
const debounce = (fn, delay) => {
let timer = null;
//借助闭包
return function () {
clearTimeout(timer);
timer = setTimeout(fn, delay);
}
}
const myThrottle = (fn, delay) => {
let flag = true;
return function () {
if (!flag) {
return false;
} else {
flag = false;
setTimeout(() => {
fn();
flag = true;
}, delay);
}
}
}
const isPowerOfFour = (num) => {
num = parseInt(num);
while(num > 1){
if(num % 4) return false;
num /= 4;
}
return true;
}
const isPowerOfFour = (num) => {
num = parseInt(num);
return num > 0 &&
(num & (num-1)) === 0 &&
(num & 0XAAAAAAAA) === 0;
}
const isPowerOfFour = (num) => {
num = parseInt(num).toString(2);
return /^1(?:00)*$/.test(num);
}
const traffic = document.getElementById('traffic');
(function reset(){
traffic.className = 's1';
setTimeout(function(){
traffic.className = 's2';
setTimeout(function(){
traffic.className = 's3';
setTimeout(function(){
traffic.className = 's4';
setTimeout(function (){
traffic.className = 's5';
setTimeout(reset,1000)
},1000)
},1000)
},1000)
},1000)
})();
const traffic = document.getElementById('traffic');
function wait(time){
return new Promise(resolve => setTimeout(resolve,time))
}
function setState(state){
traffic.className = state;
}
async function start(){
while(1){
setState('wait');
await wait(1000);
setState('stop');
await wait(3000);
setState('pass');
await wait(3000);
}
}
start();
const cards = [0,1,2,3,4,5,6,7,8,9];
const shuffle = (cards) => {
return [...cards].sort(() => { Math.random() > 0.5 ? -1 : 1 });
}
const cards = [0,1,2,3,4,5,6,7,8,9];
function *draw(cards){
const c = [...cards];
for(let i = c.length ; i > 0 ; i--){
const pIdx = Math.floor(Math.random() * i);
[c[pIdx],c[i - 1]] = [c[i - 1],c[pIdx]];
yield c[i - 1];
}
return c;
}
function generate(amount,count){
let ret = [amount];
while(count > 1){
// 挑出最大的进行切分
let cake = Math.max(...ret),
idx = ret.indexOf(cake),
part = 1 + Math.floor((cake / 2) * Math.random()),
rest = cake - part;
ret.splice(idx,1,part,rest);
count --;
}
return ret;
}
function *draw(cards){
const c = [...cards];
for(let i = c.length ; i > 0 ; i --){
const pIdx = Math.floor(Math.random()*i);
[c[pIdx],c[i-1]] = [c[i - 1],c[pIdx]];
yield c[i-1]
}
return c;
}
function generate(amount,count){
if(count <= 1) return [amount];
const cards = Array(amount - 1).fill(null).map((_,i) => i+1);
const pick = draw(cards);
const result = [];
for(let i = 0 ; i < count; i++){
result.push(pick.next().value);
}
result.sort((a,b)=>a-b);
for(let i = count - 1 ; i > 0 ; i--){
result[i] = result[i] - result[i - 1];
}
return result;
}