function checkStr(str) {
return (
str ===
str
.split("")
.reverse()
.join("")
)
}
console.log(checkStr("abcdef"))
function dedup(arr) {
return [...new Set(arr)]
}
function dedup(arr) {
return arr.reduce(
(out, cur) => (out.includes(cur) ? out : out.concat(cur)),
[]
)
}
function dedup(arr) {
const obj = {}
const result = []
for (const item of arr) {
if (!(item in obj)) {
obj[item] = result.push(item)
}
}
return result
}
const array = [
{ url: 'xxx' },
{ url: 'xxx' },
{ url: 'yyy' }
]
const dedup = (arr, key) => array.reduce((acc, item) =>
acc.find(i => i[key] === item[key]) ? acc : acc.concat(item), [])
dedup(array, 'url')
const shuffle = arr => arr.sort(() => Math.random() - 0.5)
function shuffle(arr) {
for (let i = 0; i < arr.length; i++) {
const index = parseInt(Math.random() * (arr.length - 1))
;[arr[i], arr[index]] = [arr[index], arr[i]]
}
return arr
}
function Fibonacci(n) {
const result = []
let i = 0
while (i < n) {
if (i <= 1) {
result.push(i)
} else {
result.push(result[i - 1] + result[i - 2])
}
i++
}
return result
}
function getMaxProfit(arr) {
return Math.max.apply(null, arr) - Math.min.apply(null, arr)
}
function randomString(length) {
const str = "abcdefghijklmnopqrstuvwxyz9876543210"
return Array(length)
.fill("")
.map(() => str.charAt(Math.floor(str.length * Math.random())))
.join("")
}
function queryClassName(element, className) {
return Array.from(element.getElementsByTagName("*")).filter(
e => e.className === className
)
}
function clear(arr) {
arr.splice(0, arr.length)
return arr
}
function clear(arr) {
arr.length = 0
return arr
}
Number.prototype.toFixed
function Fix(n, fractionDigits) {
return n.toFixed(fractionDigits)
}
Math.random().toString(36)输出的结果前面有小数点,所以利用 substr 截取后面的部分。
substr 和 slice 的第一个参数都是起始位置,第二个参数 substr 是长度,slice 是结束位置
function uuid(len = 10) {
let str = ""
while (str.length < len) {
str += Math.random()
.toString(36)
.substr(2)
}
// 控制长度
return str.slice(0, len)
}
function render(template, data) {
// const slot = /{{\w+}}/g
// const bracket = /{{|}}/g
// let res = slot.exec(template)
// while (res) {
// template = template.replace(res[0], data[res[0].replace(bracket, '')])
// res = slot.exec(template)
// }
// return template
return template.replace(/{{\w+}}/g, slot => data[slot.replace(/{{|}}/g, "")])
}
console.log(render(`name:{{name}}, age:{{age}}`, { name: "saber", age: 21 }))
const randSelect = list => list[parseInt(list.length * Math.random())]
/**
* 限制encode后的长度,同时保证结果可以decode
* ```ts
* // 示例
* decodeURIComponent(resolveEncode('一二三四五六七八', 45)) // 一二三四
* ```
*/
export const resolveEncode = (str: string, maxLen: number) => {
let prev = '';
let prevEncoded = '';
for (const ch of str) {
const current = prev + ch;
const currentEncoded = encodeURIComponent(current);
if (currentEncoded.length >= maxLen) {
// fallback prev
return prevEncoded;
}
prev = current;
prevEncoded = currentEncoded;
}
return prevEncoded;
};