Implement a function to deduplicate?
function unique ( array ) {
return Array. from ( new Set ( array) ) ;
}
Implement a function to determine whether the specified element exists in the array?
function includes ( array, value ) {
for ( let i = 0 , len = array. length; i < len; i++ ) {
if ( array[ i] === value) {
return true ;
}
}
return false ;
}
Implement a function to reverse a given string?
function reverseString ( str ) {
const arr = str. split ( '' ) ;
arr. reverse ( ) ;
return arr. join ( '' ) ;
}
Implement a function to detect whether the specified string is a palindrome (that is, the sequence of characters from front to back and from back to front are the same)?
function isPalindrome ( str ) {
return reverseString ( str) === str;
}
function reverseString ( str ) {
return str. split ( '' ) . reverse ( ) . join ( '' ) ;
}
Implement a function to calculate the greatest common divisor of two numbers?
function gcd ( num1, num2 ) {
return num2 ? gcd ( num2, num1 % num2) : num1;
}
Implement the Array.prototype.reduce function
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;
} ;
Implement a function delay(ms) similar to setTimeout
function delay ( ms ) {
return new Promise ( ( resolve ) => setTimeout ( resolve, ms) ) ;
}
Implement an anti-shake function debounce(fn, delayTime)
function debounce ( fn, delayTime ) {
let timerId;
return function ( ) {
const context = this ;
const args = arguments;
clearTimeout ( timerId) ;
timerId = setTimeout ( ( ) => {
fn . apply ( context, args) ;
} , delayTime) ;
} ;
}
Implement a throttling function throttle(fn, intervalTime)
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) ;
} ;
}
Implement a deep copy function deepClone(obj)
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;
}