2021-03-10 隐私协议替换文案
const result = "我已阅读并同意 %{var}, %{var2} 隐私协议1和隐私协议2".replace(/(?=\%{).+?(?<=\})/g, (key, start, string) => {
return '$' + key + '$';
});
console.log(result);
let array = result.split("$").filter(it => it.length > 0);
console.log(array);
array = array.map(it => {
const item = {};
item.value = it;
item.color = 'gray';
item.link = "";
if(it === "%{var}") {
item.link = "http://baidu.com";
item.color = "red";
item.value = "隐私协议1";
}
if( it === "%{var2}") {
item.link = "http://google.com";
item.color = "red";
item.value = "隐私协议2";
}
return item;
});
console.log(array);
2021-03-11 微信红包算法
function getWechatRedPacket(totalMoney, totalPeople) {
let minMoney = 0.01;
let maxMoney;
let currentMoney;
let sumList = [];
while(totalPeople > 1) {
maxMoney = totalMoney * 2.0 / totalPeople;
currentMoney = Math.random() * maxMoney;
currentMoney = currentMoney < 0.01 ? 0.01 : currentMoney;
console.log(currentMoney);
currentMoney = Math.round(100 * currentMoney)/100;
--totalPeople;
totalMoney -= currentMoney;
sumList.push(currentMoney);
}
sumList.push(Math.round(totalMoney * 100)/ 100);
return sumList;
}
2021-03-11通过可选链深度设置对象的值
方案一: 通过reduce去遍历
function getObj(obj = {a:{b:{c:1}}},path = 'a.b.c', value = 2) {
let arr = path.split('.');
let newObj = {...obj};
arr.reduce((preValue, it, index) => {
const flag = !preValue || !preValue[it];
if(flag) {
newObj = obj;
return preValue;
}
index === (arr.length - 1) && preValue[it] && (preValue[it] = value);
return preValue[it];
}, newObj);
return newObj;
}
2021-03-12 - 字符串中字符出现的次数
function getRepeatKeyWithString(str = '') {
let map = {};
if(!str || typeof str !== 'string') {
return [];
}
// 这里不考虑数组
str.split('').forEach(key => {
map[key] = -~map[key];
});
console.log(map);
}
2021-03-17 - 排序
// 1.快速排序
function quicklySort(array = []) {
if (array?.length <= 1) {
return array;
}
const centerIndex = Math.floor(array.length / 2);
const centerItem = array.splice(centerIndex, 1);
let leftList = [];
let rightList = [];
array.forEach((it) => {
if (it < centerItem) {
leftList.push(it);
} else {
rightList.push(it);
}
});
return quicklySort(leftList).concat(centerItem, quicklySort(rightList));
}
const list = quicklySort([1, 9, 234, 432, 12, 9, 2, 98, 34]);
// 1.冒泡排序
function bubblingSort(array = []) {
if (!array?.length) {
return array;
}
const length = array.length;
for (let i = 0; i < length - 1; i++) {
for (let j = 0; j < length - i - 1; j++) {
if (array[j + 1] < array[j]) {
[array[j], array[j + 1]] = [array[j + 1], array[j]];
}
}
}
return array;
}
const list = bubblingSort([1, 9, 234, 432, 12, 9, 2, 98, 34]);
console.log("li:", list);
// 3.flat实现
const arr = [1, [2, [3, 4]],[[[1,2]]]];
function flatten(arr) {
while (arr.some((item) => Array.isArray(item))) {
console.log("arr:", arr);
arr = [].concat(...arr);
}
return arr;
}
console.log(flatten(arr));
2021-04-29 – 6种数组拷贝的方法
Array.slice(arr);
[...arr];
Array.map(it => it);
Array.from(arr);
Object.assign([], arr);
arr.filter(it => it);