记忆函数(memoize):
let memoize = function (fn) {
let cache = {};
return function (...args) {
let key = JSON.stringify(args);
if (!cache.hasOwnProperty(key)) {
cache[key] = fn.apply(this, args);
}
return cache[key];
};
};
通过闭包cache实现对函数执行结果进行缓存,如果cache存在对应key则返回缓存的结果,否则重新执行函数。
柯里化(currying)
function currying(func) {
const args = [];
return function result(...rest) {
if (rest.length === 0) {
return func(...args);
} else {
args.push(...rest);
return result;
}
}
}
const add = (...args) => args.reduce((a, b) => a + b);
const sum = currying(add);
sum(1,2)(3); // 未真正求值
sum(4); // 未真正求值
sum(); // 真正求值
数组去重
一种方式:
let arr = [56, 8, 9, 16, 1, 1];
function unique(array) {
return array.filter(function (item, index, array) {
return array.indexOf(item) === index;
});
}
console.log(unique(arr));
二种方式:
let arr = [56, 8, 9, 16, 1, 1];
function unique(array) {
return array.filter(function (item, index, array) {
return array.indexOf(item) === index;
});
}
console.log(unique(arr));
三种方式:
let arr = [56, 8, 9, 16, 1, 1];
function unique(array) {
let res = [];
for (let i = 0, len = array.length; i < len; i++) {
let current = array[i];
if (res.indexOf(current) === -1) {
res.push(current);
}
}
return res;
}
console.log(unique(arr));
数组乱序(shuffle洗牌算法)
function shuffle(arr) {
let m = arr.length;
while (m > 1) {
let index = Math.floor(Math.random() * m--);
[arr[m], arr[index]] = [arr[index], arr[m]];
}
return arr;
}
console.log(shuffle([1, 5, 8, 9, 3, 7, 4,]));
扁平数组转JSON树结构(convert)
要求:把id放到对应parent_id下的children中
let flatArr = [
{id: 1, title: "解忧杂货铺1", parent_id: 0},
{id: 2, title: '解忧杂货铺2', parent_id: 0},
{id: 3, title: '解忧杂货铺2-1', parent_id: 2},
{id: 4, title: '解忧杂货铺3-1', parent_id: 3},
{id: 5, title: '解忧杂货铺4-1', parent_id: 4},
{id: 6, title: '解忧杂货铺2-2', parent_id: 2},
];
function convert(list) {
const res = [];
const map = {};
for (let i in list) {
if (list.hasOwnProperty(i)) {
map[list[i].id] = list[i];
}
}
for (const item of list) {
if (item.parent_id === 0) {
res.push(item);
continue;
}
if (item.parent_id in map) {
const parent = map[item.parent_id];
parent.children = parent.children || [];
parent.children.push(item);
}
}
return res;
}
let returnTree = convert(flatArr);
图片懒加载(lazyLoad)
let imgs = document.querySelectorAll('img');
// 可视区高度
let clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
function lazyLoad() {
// 滚动卷去的高度
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
for (let i = 0; i < imgs.length; i++) {
// 图片在可视区冒出的高度
let x = clientHeight + scrollTop - imgs[i].offsetTop;
// 图片在可视区内
if (x > 0 && x < clientHeight + imgs[i].height) {
imgs[i].src = imgs[i].getAttribute('data');
}
}
}
window.addEventListener('scroll', lazyLoad);
对象排序
const obj = [
{"name": "张三", "class": 2, "score": 64},
{"name": "李四", "class": 1, "score": 80},
{"name": "王五", "class": 1, "score": 80},
{"name": "赵六", "class": 4, "score": 94},
];
/*题目要求:班级从小到大 班级相同时 按成绩从大到小 班级成绩都相同 按照原有的顺序进行排列*/
obj.sort(function (a, b) {
if (a.class < b.class) {
return -1;
}
if (a.class === b.class) {
if (a.score > b.score) {
return 1;
}
}
if(a.class === b.class && a.score === b.score){
return 0
}
});
console.log(obj);
判断两个对象是否相等
const objOne = {
a: 1,
b: 2,
c: 3
};
const objTwo = {
a: 1,
b: 2,
c: 3,
d: 4
};
const isObjEqual = (objOne, objTwo) => {
const objOneKeys = Object.keys(objOne);
const objTwoKeys = Object.keys(objTwo);
if (objOneKeys.length !== objTwoKeys.length) {
return false;
} else {
return !objOneKeys.some(key => objOne[key] !== objTwo[key]);
}
};
let objEqual = isObjEqual(objOne, objTwo);
console.log(objEqual);
回文数判断(Palindrome)
const isPalindrome = function (x) {
x = x.toString();
let i = 0, r = x.length - 1;
while (i <= r) {
if (x[i] !== x[r]) {
return false;
} else {
i++;
r--;
}
}
return true;
};
console.log(isPalindrome(121));
清空首位空格
const trim = (str) => {
while (true) {
if (str.startsWith(" ")) {
str = str.substring(1);
} else {
break;
}
}
while (true) {
if (str.endsWith(" ")) {
str = str.substring(0, str.length - 1);
} else {
break;
}
}
return str;
};
const trimStr = trim('1 23v 45 ');
console.log(trimStr);
对象元素标号
原数组=> ['A', 'B', 'C', 'B', 'C', 'A', 'B']
转换为新数组=> ['A-1',"B-1","C-1","B-2","C-2","A-2","B-3"]
const arr = ['A', 'B', 'C', 'B', 'C', 'A', 'B'];
const map = {};
for (let i = 0; i < arr.length; i++) {
let current = arr[i];
if (!map[current]) {
map[current] = {
element: current,
count: 1,
firstIndex: i
};
} else {
if (map[current].firstIndex || map[current].firstIndex === 0) {
arr[map[current].firstIndex] = current + '-' + 1;
map[current].firstIndex = false;
}
map[current].count = map[current].count + 1;
arr[i] = current + '-' + map[current].count;
}
}
console.log(arr);
嘿嘿嘿 窝窝头 嘿嘿 一块钱四个。。。