当前位置:网站首页>JS basic algorithm (1)

JS basic algorithm (1)

2020-11-10 10:45:00 Huang Wantong

One 、 Humping

  • user-top-info-name Turn into a hump userTopInfoName

Method 1- Using the array

function toCamelCase(str) {
  if (!str) return ''
  //  First convert the string to lowercase 
  str = str.toLowerCase()
  //  Use  split  Convert string to array 
  let strArr = str.split('-')
  //  Use  map  Traversal array , The first one in the array doesn't need to be converted , All the others turn 
  /*
    strArr =  strArr.map((item,index) => {
    if(index !==0) {
      return item[0].toUpperCase()+item.substr(1)
    }else {
      return item
    }
    })
  */
  //  Simplify writing 
  strArr = strArr.map((item, index) =>
    index !== 0 ? item[0].toUpperCase() + item.substr(1) : item
  )
  //  array-based  join  Method converts the processed array into a string and returns 
  return strArr.join('')
}
//  test 
console.log(toCamelCase('user-top-info-name')) //  Output :userTopInfoName

Method 2- Use regular

function toCamelCase2(str) {
  if (!str) return ''
  //  First convert the string to lowercase 
  str = str.toLowerCase()
  str = str.replace(/(\-\w)/g, (chars) => chars[1].toUpperCase())
  return str
}
//  test 
console.log(toCamelCase('user-top-info-name')) //  Output :userTopInfoName

Two 、 Array weight removal

function uniqueArray(arr) {
  //  Use Set Duplicate the array , And then use Array.from Methods will set Convert to array and return 
  // return Array.from(new Set(arr))
  return [...new Set(arr)] //  You can also use the three-point operator 
}
//  test 
console.log(uniqueArray([2, 2, 3, 3, 4, 4, 5, 5, 6, 6]))

3、 ... and 、 Count the most letters in the string

function getlongestChar(str) {
  if (!str) return ''
  if (str.length === 1) return str
  //  Define an object to store characters 
  let obj = {}
  //  Loop through the string 
  for (let i = 0; i < str.length; i++) {
    //  Get the current character 
    let char = str.charAt(i)
    //  Determine whether the current character is obj Properties of , If so, it is the attribute +1, If the current property is not assigned a value of 1
    obj[char] ? obj[char]++ : (obj[char] = 1)
  }
  //  Get the maximum value 
  const max = Math.max(...Object.values(obj))
  //  The character that gets the most value 
  const resultChar = Object.keys(obj).find((item) => obj[item] === max)
  //  Return character 
  return resultChar
}
console.log(getlongestChar('bbbdddjjjaaab'))

Four 、 Reverse string order

function reverseString(str) {
  //  Split a string into arrays , Then call the flip method of the array , Finally, the array is converted to a string 
  return str.split('').reverse().join('')
  /*
     You can also use reverse order 
  */
  // let result = ''
  // for(let i = str.length-1; i >= 0;i++) {
  //   result += str[i]
  // }
  // return result
}
console.log(reverseString('Hello World'))

5、 ... and 、 Deep copy

function deepCopy(target) {
  /*
     Determine whether the target element is an array or an object and the target element is not null
  */
  if (
    target instanceof Array ||
    (target !== null && typeof target === 'object')
  ) {
    //  Create an array or object based on the type of target data 
    let cloneTarget = target instanceof Array ? [] : {}
    //  Loop through the target element , for...in... Loops can traverse arrays and objects 
    for (let key in target) {
      //  recursive copying 
      cloneTarget[key] = deepCopy(target[key])
    }
    //  Return the copied element 
    return cloneTarget
  } else {
    //  If it is not an array or object type, return the element directly 
    return target
  }
}
console.log(deepCopy({ name: 'kobe', age: 42 }))

6、 ... and 、 Merge multiple ordered arrays -- Sort -- duplicate removal

function flatArray(arr) {
  //  Create an empty array 
  let resultArr = []
  //  Loop through a two-dimensional array 
  arr.forEach((item) => {
    //  Convert a two-dimensional array into a one-dimensional array 
    item instanceof Array ? resultArr.push(...item) : resultArr.push(item)
  })
  //  duplicate removal 
  resultArr = [...new Set(resultArr)]
  //  Sort and return 
  return resultArr.sort((a, b) => a - b)
}

console.log(
  flatArray([
    [1, 2, 3],
    [6, 2, 1, 3, 4],
    [2, 1, 4, 5, 3, 6],
  ])
)

7、 ... and 、 Array sorting

function sortArray(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        let temp = arr[j]
        arr[j] = arr[j + 1]
        arr[j + 1] = temp
      }
    }
  }
  return arr
}
console.log(sortArray([22, 55, 11, 33, 44, 55, 66, 77, 11, 44]))

8、 ... and 、 Joseph Ring problem

  • describe : The number is 1 To 100 A hundred people in a circle , With 123123 The way to count off , Count to 3 People who quit the circle automatically , The rest continued to count , Ask the number of the last person left ?
function josephRing(n, k) {
  //  Create an array 
  let arr = []
  //  Remove the first appearance 
  for (let i = 1; i <= n; i++) {
    if (i % k !== 0) arr.push(i)
  }
  //  Define a counter 
  let flag = 0
  while (arr.length > 1) {
    let outNum = 0 //  The number of people out of this cycle , Easy to locate the element position 
    let len = arr.length
    for (let i = 0; i < len; i++) {
      flag++
      if (flag === k) {
        flag = 0
        arr.splice(i - outNum, 1)
        outNum++
      }
    }
  }
  return arr[0]
}
console.log(josephRing(100))

Nine 、 Palindrome string

  • Palindrome string : It's a string that is read both forward and backward .

Method 1: Determine whether the string and flipped are equal

function palindromeString(str) {
  /*
    1.  Determine whether the string and flipped are equal 
  */
  return str === str.split('').reverse().join('')
}
console.log(palindromeString('aba'))

Method 2: Loop through the string , Determine whether the first character and the last character are equal in turn , Whether the second and the last two are equal ...

function palindromeString2(str) {
  const len = str.length
  let flag = true
  //  Loop through the string , It's only half way through 
  for (let i = 0; i < len / 2; i++) {
    //  Judge in turn  str[0] !== str[str.length-1-0],str[1] !== str[str.length-1-1]...
    if (str[i] !== str[len - 1 - i]) {
      //  If there is a group that is not equal to flag The assignment is false
      flag = false
      break //  End of cycle 
    }
  }
  //  return flag
  return flag
}
console.log(palindromeString2('aba'))

Ten 、 Without the aid of temporary variables , Exchange two integers

function swap(a, b) {
  // 10   20
  // [a,b] = [b,a]
  a = a - b // a = -10
  b = b + a // b = 10
  a = b - a // a = 20
  return [a, b]
}
console.log(swap(30, 20))

11、 ... and 、 Find the maximum difference in the array

//  Find the maximum difference in the array 
function getMaxDiff(arr) {
  /*
    1.  adopt Math.max() and  Math.min() Add the three-point operator 
  */
  // return Math.max(...arr) - Math.min(...arr)

  /*
    2.  After sorting the array, calculate the difference between the last and the first 
  */
  arr.sort((a, b) => a - b)
  return arr[arr.length - 1] - arr[0]
}
console.log(getMaxDiff([50, 60, 10, 20, 40, 80, 90]))

Twelve 、 Randomly generates a string of specified length

Method 1

//  Randomly generates a string of specified length 
function randomStr(len) {
  //  Define the source string 
  let sourceStr =
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  /*
    1.  Using arrays , Scramble the array to get the front len individual 
   */
  let arr = sourceStr.split('')
  //  Put the array out of order 
  arr.sort(() => 0.5 - Math.random())
  //  Get array len Array elements are converted into strings 
  return arr.filter((item, index) => index < len).join('')
}
console.log(randomStr(6))

Method 2

//  Randomly generates a string of specified length 
function randomStr2(len) {
  //  Define the source string 
  let sourceStr =
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  /*
    2.  Loop to get random subscripts 
  */
  let returnStr = ''
  while (returnStr.length < len) {
    let index = Math.floor(Math.random() * sourceStr.length)
    returnStr += sourceStr[index]
  }
  return returnStr
}
console.log(randomStr2(6))

Welcome the boss to correct

版权声明
本文为[Huang Wantong]所创,转载请带上原文链接,感谢