function unique(array) {
return Array.from(new Set(array));
}
function includes(array, value) {
for (let i = 0, len = array.length; i < len; i++) {
if (array[i] === value) {
return true;
}
}
return false;
}
function reverseString(str) {
// 将字符串分割成一个数组
const arr = str.split('');
// 反转数组
arr.reverse();
// 将数组拼接成字符串
return arr.join('');
}
function isPalindrome(str) {
// 将字符串反转后与原字符串比较
return reverseString(str) === str;
}
// 利用上题的实现
function reverseString(str) {
return str.split('').reverse().join('');
}
function gcd(num1, num2) {
return num2 ? gcd(num2, num1 % num2) : num1;
}
Array.prototype.myReduce = function(fn, initialValue) {
let accum = initialValue === undefined ? undefined : initialValue;
for (let i = 0; i < this.length; i++) {
if (accum !== undefined) {
accum = fn.call(undefined, accum, this[i], i, this);
} else {
accum = this[i];
}
}
return accum;
};
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function debounce(fn, delayTime) {
let timerId;
return function() {
const context = this;
const args = arguments;
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(context, args);
}, delayTime);
};
}
function throttle(fn, intervalTime) {
let timerId;
let canRun = true;
return function() {
const context = this;
const args = arguments;
if (!canRun) return;
canRun = false;
timerId = setTimeout(function() {
fn.apply(context, args);
canRun = true;
}, intervalTime);
};
}
function deepClone(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
let result = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}