๐ŸŒŒ Day 6 Algorithm Review

11910 ๋‹จ์–ด BackendalgorithmStringBackend

๐ŸŒš Replit

array.map()

// Convert string into number
function solution(element, index, array) {
		return Number(element)
}

// Convert the last string into number
function solution(element, index, array) {
	if (index === array.length-1){
      element = Number(element)
    }
 return element
}

const arr = ['1', '2', '3'];
const result = arr.map(solution);
console.log(result); // [1, 2, 3]

String Detection Method

const email = '[email protected]'; 

console.log(email.startsWith('pre'));   //true
console.log(email.endsWith('com'));     //true
console.log(email.includes('@gmail'));  //true
console.log(email.endsWith('@gmail.com'));  //true

๐ŸŒ Class

padStart

let str = ""
str.padStart(5, 'z')	// 'zzzzz'

str.padStart(5, "*") // '*****'

slice

// 1. ๋ฐฐ์—ด, ๋ฌธ์ž์—ด์„ ์ž๋ฅผ ๋•Œ ์‚ฌ์šฉ
// 2. ์›๋ณธ์ด ์ €์žฅ๋˜์ง€ ์•Š์Œ

str = "abcde"
str.slice(2)

๐Ÿƒ Ternary Operator

// ์‚ผํ•ญ ์—ฐ์‚ฐ์ž ์‚ฌ์šฉ
function solution(num){
    return num % 2 === 0? "Even" : "Odd"
}

๐Ÿƒ Masking phone number

function solution(phone_number){
    let answer = ''
    
    for (let i = 0; i<phone_number.length; i++){
        if (i< phone_number.length -4){
            answer += '*'
        }
        else {
            answer += phone_number[i]
        }
    }
    return answer
}

// => refactoring
function solution(phone_number){
    let answer = ''
    
    answer = answer.padStart(phone_number-4, "*")
    answer += phone_number.slice(phone_number.length -4, phone_number.length)
    return answer
}

๐Ÿƒ reduce() method

// ======== ํ‰๊ท ๊ฐ’ ๊ตฌํ•˜๊ธฐ ========
function solution(arr){
    //reduce = for loop 
    // ๊ณ„์† ๋ฐ˜๋ณตํ•˜๋Š”๊ฑด๋ฐ reduce๋Š” acc(๋ˆ„์ ๊ฐ’)์ด๋ผ๋Š”๊ฑฐ ์ž์ฒด๊ฐ€ ์ด์ „ ๊ฐ’์„ ๊ณ„์† ๋ฐ›์•„์˜ค๋Š”๊ฑฐ์ž„
      const sum = arr.reduce( (acc, cur) => {
          console.log(acc, cur)	// acc = ๋ˆ„์ ๊ฐ’ // cur = ํ˜„์žฌ ๊ฐ’
            return acc + cur
      },0)
      return sum/arr.length
  }

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ