分糖果问题
输入:[1,1,2]
返回值:4
说明:arr为得分列表,需要根据得分情况,得分高的糖果分得多
function candy( arr ) {
// write code here
let len = arr.length;
if(len<=1) return len;
let candyNum = 1
// 记录糖果数量
let candyArr = new Array(len).fill(candyNum)
// 遍历查询所有孩子的得分
// 从左到右看,保证糖果根据分值递增
// 小--->大
for(let i=1; i<len; i++) {
if(arr[i] <= arr[i-1]) continue
// 小--->大
candyArr[i]= candyArr[i-1]+1
}
// 从右向左看,保证糖果根据分值递递增
// 大<---小
for(let i=len-2;i>=0;i--) {
if(arr[i] <= arr[i+1])continue
// 过滤糖果非递增项
if(candyArr[i] > candyArr[i+1]) continue
// 大<---小
candyArr[i] = candyArr[i+1]+1
}
return candyArr.reduce((pre,cur)=>pre+cur,0)
}
函数链式调用
// 实现效果
LazyMan(“Hank”).eat(“supper”).sleepFirst(5)输出
//等待5秒
Wake up after 5
Hi This is Hank!
Eat supper
let fn1 = (str) => console.log(`Hi! This is ${str}!`);
let fn2 = (delay) => new Promise((resolve) =>
setTimeout(() => {
console.log(`Wake up after ${delay}`);
resolve();
}, delay)
);
let fn3 = (str) => console.log(`Eat ${str}~!`);
function Task() {
this.stack = [];
this.LazyMan = function(param) {
this.stack.push(fn1.bind(null, param));
return this;
};
this.sleep = function(param) {
this.stack.push(fn2.bind(null, param));
return this;
};
this.eat = function(param) {
this.stack.push(fn3.bind(null, param));
return this;
};
this.sleepFirst = function(param) {
this.stack.unshift(fn2.bind(null, param));
return this;
};
this.start = function() {
this.stack.reduce((pre, cur) =>
pre instanceof Promise ? pre.then((res) => cur(res)) : cur(pre), null)
.then();
this.stack.length =0
};
}
let f1 = new Task();
f1.LazyMan("Hank").sleep(5).eat("supper").sleepFirst(5);
f1.start().then();