[JavaScript] Solution to puzzles πŸ”₯

Joy🌱·2023λ…„ 2μ›” 19일
0

🧩 Coding Challenges

λͺ©λ‘ 보기
18/20
post-thumbnail
post-custom-banner

πŸ‘€ ν•¨μˆ˜

🧩 min, max function

πŸ’β€ 전달 된 λ§€κ°œλ³€μˆ˜ 쀑 μ΅œμ†Œκ°’μ„ λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜ min(a, b)κ³Ό 전달 된 λ§€κ°œλ³€μˆ˜ 쀑 μ΅œλŒ€κ°’μ„ λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜ max(a, b)λ₯Ό μ •μ˜ν•˜κ³ 
λ³€μˆ˜ μ΄ˆκΈ°ν™” 숫자λ₯Ό λ³€κ²½ν•˜λ©° μ΅œμ†Œκ°’κ³Ό μ΅œλŒ€κ°’μ„ ν•¨μˆ˜ ν˜ΈμΆœμ„ 톡해 리턴 λ°›μ•„ μ½˜μ†”μ— 좜λ ₯ν•˜λŠ” ν…ŒμŠ€νŠΈλ₯Ό ν•˜μ„Έμš”.

🚩 Example Output

μ΅œμ†Œκ°’ : 10
μ΅œλŒ€κ°’ : 20
// μ΅œμ†Œκ°’μ„ λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜
function min(a, b) {
    a < b ? result = a : result = b
    return result;
};

// μ΅œλŒ€κ°’μ„ λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜
function max(a, b) {
    a > b ? result = a : result = b
    return result;
};

// 전달 받은 ν•¨μˆ˜μ— 전달 받은 값을 적용 μ‹œμΌœμ£ΌλŠ” κ³ μ°¨ ν•¨μˆ˜
function apply(func, a, b) {

    return func(a, b);
}

const num1 = 10;
const num2 = 20;
console.log(`μ΅œμ†Œκ°’ : ${apply(min, num1, num2)}`);
console.log(`μ΅œλŒ€κ°’ : ${apply(max, num1, num2)}`);

🧩 pow function

πŸ’β€ x의 nμ œκ³±μ„ λ°˜ν™˜ν•΄μ£ΌλŠ” ν•¨μˆ˜ pow(x, n)λ₯Ό μ •μ˜ν•˜κ³  λ³€μˆ˜ μ΄ˆκΈ°ν™” 숫자λ₯Ό λ³€κ²½ν•˜λ©° ν•¨μˆ˜ ν˜ΈμΆœν•˜μ—¬ μ½˜μ†”λ‘œ 리턴 받은 κ²°κ³Ό 값을 좜λ ₯ν•˜μ„Έμš”.

  • x의 n μ œκ³±μ€ xλ₯Ό n번 κ³±ν•΄μ„œ λ§Œλ“€ 수 μžˆμŠ΅λ‹ˆλ‹€.
  • μ£Όμ˜μ‚¬ν•­ : n은 1 μ΄μƒμ˜ μžμ—°μˆ˜μ—¬μ•Ό ν•˜λ―€λ‘œ μ΄μ™Έμ˜ κ²½μš°μ—” μžμ—°μˆ˜λ₯Ό μž…λ ₯ν•˜λΌλŠ” 문ꡬλ₯Ό μ½˜μ†”λ‘œ 좜λ ₯ν•©λ‹ˆλ‹€.

🚩 Example Output

1024
λ˜λŠ”
-1은 μ–‘μ˜ μ •μˆ˜μ΄μ–΄μ•Ό ν•©λ‹ˆλ‹€.
// x의 nμ œκ³±μ„ λ°˜ν™˜ν•΄μ£ΌλŠ” ν•¨μˆ˜
function pow(x, n) {

    let result = 1;
    if(n > 0) {
        for(let i = 0; i < n; i++){
            result = result * x;
        }
    } else {
        result = `${n}은 μ–‘μ˜ μ •μˆ˜μ΄μ–΄μ•Ό ν•©λ‹ˆλ‹€.`
    }

    return result;
}

const x = 2;
const n = 10;

console.log(pow(x, n));

🧩 min, max function ν™”μ‚΄ν‘œ ν•¨μˆ˜

πŸ’β€ 2-1μ—μ„œ ν•¨μˆ˜ μ„ μ–Έλ¬ΈμœΌλ‘œ μž‘μ„±ν•œ min, max ν•¨μˆ˜λ₯Ό ν™”μ‚΄ν‘œ ν•¨μˆ˜λ‘œ λ³€κ²½ν•˜μ—¬ 생성 ν›„ λ³€μˆ˜ μ΄ˆκΈ°ν™” 숫자λ₯Ό λ³€κ²½ν•˜λ©° μ΅œμ†Œκ°’κ³Ό μ΅œλŒ€κ°’μ„ ν•¨μˆ˜ ν˜ΈμΆœμ„ 톡해 리턴 λ°›μ•„ μ½˜μ†”μ— 좜λ ₯ν•˜λŠ” ν…ŒμŠ€νŠΈλ₯Ό ν•©λ‹ˆλ‹€.

  • μ‚Όν•­ μ—°μ‚°μžλ₯Ό μ΄μš©ν•˜λ©΄ ν•˜λ‚˜μ˜ ꡬ문으둜 λ³€κ²½ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

🚩 Example Output

μ΅œμ†Œκ°’ : 10
μ΅œλŒ€κ°’ : 20
// μ΅œμ†Œκ°’μ„ λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜
min = (a, b) => { a < b ? result = a : result = b; return result;};

// μ΅œλŒ€κ°’μ„ λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜
max = (a, b) => { a > b ? result = a : result = b; return result;};

// 전달 받은 ν•¨μˆ˜μ— 전달 받은 값을 적용 μ‹œμΌœμ£ΌλŠ” κ³ μ°¨ ν•¨μˆ˜
apply = (func, a, b) => func(a, b);

const a = 10;
const b = 20;
console.log(`μ΅œμ†Œκ°’ : ${apply(min, a, b)}`);
console.log(`μ΅œλŒ€κ°’ : ${apply(max, a, b)}`);

πŸ‘€ 객체

🧩 객체 λ¦¬ν„°λŸ΄λ‘œ 계산기 객체 λ§Œλ“€κΈ°

πŸ’β€ calculator λΌλŠ” 객체에 μ•„λž˜μ™€ 같은 λ©”μ†Œλ“œλ₯Ό μ •μ˜ν•˜κ³  λ©”μ†Œλ“œ 싀행을 ν…ŒμŠ€νŠΈ ν•˜μ„Έμš”.

  • sum λ©”μ†Œλ“œ : 객체의 a, b 두 κ°’μ˜ 합을 λ°˜ν™˜
  • multi λ©”μ†Œλ“œ : 객체의 a, b 두 κ°’μ˜ 곱을 λ°˜ν™˜

🚩 Example Output

ν•© : 30
κ³± : 200
const calculator = {
    a : 10,
    b : 20,
    sum : function() { 
        return `ν•© : ${this.a + this.b}`},
    multi : function() { 
        return `κ³± : ${this.a * this.b}`}
};

console.log(calculator.sum());
console.log(calculator.multi());

🧩 객체 μƒμ„±μžλ‘œ 계산기 객체 λ§Œλ“€κΈ°

πŸ’β€ CalculatorλΌλŠ” μƒμ„±μž ν•¨μˆ˜μ— μ•„λž˜μ™€ 같은 λ©”μ†Œλ“œλ₯Ό μ •μ˜ν•˜κ³  ν•΄λ‹Ή μƒμ„±μžλ₯Ό 톡해 객체λ₯Ό λ§Œλ“€μ–΄ λ©”μ†Œλ“œ 싀행을 ν…ŒμŠ€νŠΈ ν•˜μ„Έμš”

  • sum λ©”μ†Œλ“œ : μ €μž₯된 두 κ°’μ˜ 합을 λ°˜ν™˜
  • multi λ©”μ†Œλ“œ : μ €μž₯된 두 κ°’μ˜ 곱을 λ°˜ν™˜

🚩 Example Output

ν•© : 30
κ³± : 200
function Calculator() {
    this.a = 10;
    this.b = 20;
    this.sum = function() { 
        return `ν•© : ${this.a + this.b}`},
    this.multi = function() { 
        return `κ³± : ${this.a * this.b}`}
}

const sum = new Calculator().sum();
const multi = new Calculator().multi();

console.log(sum);
console.log(multi);

πŸ‘€ λ°°μ—΄

🧩 split, indexOf

πŸ’β€ 전달 받은 λ¬Έμžμ—΄(str) μ•ˆμ— μžˆλŠ” 값을 ',' κΈ°μ€€μœΌλ‘œ λ°°μ—΄λ‘œ λΆ„λ¦¬ν•˜κ³  전달받은 단어(word)κ°€ μžˆλŠ” index μœ„μΉ˜λ₯Ό λ¬Έμžμ—΄λ‘œ λ¦¬ν„΄ν•˜λŠ” ν•¨μˆ˜ findWord(str, word)λ₯Ό μž‘μ„±ν•˜μ„Έμš”.

🚩 Example Output

κ³ μ–‘μ΄λŠ” λ°°μ—΄ index 10λ²ˆμ§Έμ— μžˆμŠ΅λ‹ˆλ‹€.
μƒŒλ“œμœ„μΉ˜λŠ” 배열에 μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.
κ²°κ³Όλ₯Ό 확인할 수 μ—†μŠ΅λ‹ˆλ‹€.
const str = '사과,λ°”λ‚˜λ‚˜,λ‹Ήκ·Ό,κΉ€λ°₯,치즈,떑볢이,햄버거,ν™˜νƒ€,사이닀,콜라,고양이,강아지';

console.log(findWord(str, '고양이'));     
console.log(findWord(str, 'μƒŒλ“œμœ„μΉ˜'));  
console.log(findWord(str));             

function findWord(str, word) {
  
  if (!word) {
    return "κ²°κ³Όλ₯Ό 확인할 수 μ—†μŠ΅λ‹ˆλ‹€.";
  }

  let wordArr = str.split(",");

  let index = wordArr.indexOf(word);

  if (index >= 0)
    return `${word}λŠ” λ°°μ—΄ index ${index}λ²ˆμ§Έμ— μžˆμŠ΅λ‹ˆλ‹€.`;
  else
    return `${word}λŠ” 배열에 μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.`;
}

🧩 splice

πŸ’β€ λ°°μ—΄(arr)의 μš”μ†Œ 쀑 a와 b 사이에 μ†ν•˜μ§€ μ•ŠλŠ” μš”μ†ŒλŠ” μ‚­μ œν•΄μ£ΌλŠ” ν•¨μˆ˜ filterRange(arr, a, b)λ₯Ό μž‘μ„±ν•˜μ„Έμš”.

🚩 Example Output

[5, 3, 1, 4]
function filterRange(arr, a, b) {

    for(let i = 0; i < arr.length; i++) {
        if(arr[i] < a || arr[i] > b)  {
          arr.splice(i, 1);
          i--;
        }
      }
  }
  const arr = [5, 3, 8, 1, 10, 4];
  
  filterRange(arr, 1, 5); 
  
  console.log(arr); 

πŸ’‘ Another Solution

function filterRange(arr, a, b) {

    arr.forEach((item, index) => {
        if (item < a || item > b) {
            arr.splice(index, 1);
        }
    });
      
}

const arr = [5, 3, 8, 1, 10, 4];

filterRange(arr, 1, 5); // 1κ³Ό 5 사이에 μžˆμ§€ μ•Šμ€ μš”μ†ŒλŠ” λͺ¨λ‘ μ œκ±°ν•¨

console.log(arr); // [5, 3, 1, 4]

🧩 sort

πŸ’β€ μ œμ‹œ 된 μˆ«μžκ°’ λ°°μ—΄κ³Ό λ¬Έμžκ°’ 배열을 μ˜€λ¦„μ°¨μˆœ μ •λ ¬, λ‚΄λ¦Όμ°¨μˆœ μ •λ ¬ν•˜μ—¬ 좜λ ₯ν•˜μ„Έμš”.

🚩 Example Output

[ 9, 20, 37, 54, 88, 100 ]
[ 100, 88, 54, 37, 20, 9 ]
[ 'hello', 'js', 'party', 'wow' ]
[ 'wow', 'party', 'js', 'hello' ]
let numbers = [20, 100, 37, 54, 88, 9];
let strings = ['wow', 'js', 'party', 'hello'];

console.log(numbers.sort((a, b) => a - b)); // 숫자 μ˜€λ¦„μ°¨μˆœ
console.log(numbers.sort((a, b) => b - a)); // 숫자 λ‚΄λ¦Όμ°¨μˆœ
console.log(strings.sort());                // λ¬Έμžμ—΄ μ˜€λ¦„μ°¨μˆœ
console.log(strings.reverse());             // λ¬Έμžμ—΄ λ‚΄λ¦Όμ°¨μˆœ

πŸ’‘ Another Solution

let numbers = [20, 100, 37, 54, 88, 9];
let strings = ['wow', 'js', 'party', 'hello'];

// 숫자 μ˜€λ¦„μ°¨μˆœ
numbers.sort((a, b) => a - b);           
console.log(numbers);
// 숫자 λ‚΄λ¦Όμ°¨μˆœ
numbers.sort((a, b) => b - a);
// numbers.reverse(); - μ—­μˆœ μ²˜λ¦¬λ„ κ°€λŠ₯
console.log(numbers);

// 문자 μ˜€λ¦„μ°¨μˆœ
strings.sort();
console.log(strings);
// 문자 λ‚΄λ¦Όμ°¨μˆœ
strings.sort(function (a, b) {
  if(a > b) return -1;
  if(a == b) return 0;
  if(a < b) return 1;
});
// strings.reverse(); - μ—­μˆœ μ²˜λ¦¬λ„ κ°€λŠ₯
console.log(strings);

🧩 sort, map

πŸ’β€ Student μƒμ„±μž ν•¨μˆ˜λ₯Ό 톡해 생성 된 3λͺ…μ˜ 학생 객체λ₯Ό studentList 배열에 λ‹΄μ•˜μŠ΅λ‹ˆλ‹€. ν•΄λ‹Ή 배열을 μ „λ‹¬ν•˜μ—¬ score λ‚΄λ¦Όμ°¨μˆœ κΈ°μ€€μœΌλ‘œ μ •λ ¬ν•΄μ£ΌλŠ” sortFromScore(arr) ν•¨μˆ˜, ν•΄λ‹Ή 배열을 μ „λ‹¬ν•˜μ—¬ lastNameκ³Ό firstName을 ν•©μ„±ν•˜μ—¬ name μ†μ„±μœΌλ‘œ λ§Œλ“€μ–΄ λ°˜ν™˜ν•˜λŠ” makeFullName ν•¨μˆ˜λ₯Ό μž‘μ„±ν•˜μ„Έμš”.

🚩 Example Output

[
  Student { firstName: 'κ΄€μˆœ', lastName: '유', score: 80 },
  Student { firstName: '보고', lastName: 'μž₯', score: 70 },
  Student { firstName: '길동', lastName: '홍', score: 60 }
]
[
  { name: 'μœ κ΄€μˆœ', score: 80 },
  { name: 'μž₯보고', score: 70 },
  { name: '홍길동', score: 60 }
]
function Student(firstName, lastName, score){
  this.firstName = firstName;
  this.lastName = lastName;
  this.score = score;
}

const studentList = [
  new Student('길동', '홍', 60),
  new Student('보고', 'μž₯', 70),
  new Student('κ΄€μˆœ', '유', 80)
];

sortFromScore(studentList);
console.log(studentList);
console.log(makeFullName(studentList));

function sortFromScore (arr) {	
  arr.sort((a , b) => b.score - a.score);
}

function makeFullName(arr){
  return arr.map(user => ({ 
    name : user.lastName + user.firstName,
    score : user.score })
  );
}

πŸ‘€ ν‘œμ€€ 빌트인 객체

🧩 Date

πŸ’β€ λ…„, μ›”, 일을 μ „λ‹¬ν•˜λ©΄ ν•΄λ‹Ή λ‚ μ§œμ˜ μš”μΌμ„ 'μ›”', 'ν™”', '수', 'λͺ©', '금', 'ν† ', '일' λ¬Έμžμ—΄λ‘œ λ°˜ν™˜ν•΄μ£ΌλŠ” ν•¨μˆ˜ getWeekDayλ₯Ό λ§Œλ“œμ„Έμš”.

🚩 Example Output

ν™”
μ›”
console.log(getWeekDay(2022, 6, 21));       // 2022λ…„ 6μ›” 21일
console.log(getWeekDay(2022, 12, 12));      // 2022λ…„ 12μ›” 12일 

function getWeekDay(year, month, date) {

    const weekDayArr = new Array('일', 'μ›”', 'ν™”', '수', 'λͺ©', '금', 'ν† ');

    const idx = new Date(`${year}-${month}-${date}`).getDay();
    const weekDay = weekDayArr[idx]; 

    return weekDay;
}

πŸ’‘ Another Solution

console.log(getWeekDay(2022, 6, 21));       // 2022λ…„ 6μ›” 21일
console.log(getWeekDay(2022, 12, 12));      // 2022λ…„ 12μ›” 12일 

function getWeekDay(year, month, date) {

  let when = new Date(year, month - 1, date);
  let days = ['일', 'μ›”', 'ν™”', '수', 'λͺ©', '금', 'ν† '];
  return days[when.getDay()];

}

🧩 Date

πŸ’β€ 였늘 흐λ₯Έ μ‹œκ°„μ„ 초 λ‹¨μœ„λ‘œ μ•Œλ €μ£ΌλŠ” getSecondsToday ν•¨μˆ˜μ™€ 였늘 남은 μ‹œκ°„μ„ μ΄ˆλ‹¨μœ„λ‘œ μ•Œλ €μ£ΌλŠ” getSecondsToTomorrow ν•¨μˆ˜λ₯Ό λ§Œλ“œμ„Έμš”.

🚩 Example Output

xxxxxμ΄ˆλ‚˜ ν˜λ €μŠ΅λ‹ˆλ‹€. μ‹œκ°„μ„ μ†Œμ€‘νžˆ μ”μ‹œλ‹€^^
xxxxx초 밖에 μ•ˆ λ‚¨μ•˜μŠ΅λ‹ˆλ‹€. λ‹€μ‹œλŠ” μ˜€μ§€ μ•ŠλŠ” μ˜€λŠ˜μž…λ‹ˆλ‹€^^
console.log(getSecondsToday());
console.log(getSecondsToTomorrow());

function getSecondsToday() {
  let now = new Date();
  let today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  let diff = now - today; 
  return `${Math.round(diff / 1000)}μ΄ˆλ‚˜ ν˜λ €μŠ΅λ‹ˆλ‹€. μ‹œκ°„μ„ μ†Œμ€‘νžˆ μ”μ‹œλ‹€^^`; 
}

function getSecondsToTomorrow() {
  let now = new Date();
  let tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1);
  let diff = tomorrow - now;
  return `${Math.round(diff / 1000)}초 밖에 μ•ˆ λ‚¨μ•˜μŠ΅λ‹ˆλ‹€. λ‹€μ‹œλŠ” μ˜€μ§€ μ•ŠλŠ” μ˜€λŠ˜μž…λ‹ˆλ‹€^^`;
}

🧩 μ •κ·œ ν‘œν˜„μ‹

πŸ’β€ μƒκ·Όμ΄λŠ” 생λͺ…κ³Όν•™ μ—°κ΅¬μ†Œμ—μ„œ 염색체가 νŠΉμ •ν•œ νŒ¨ν„΄μΈμ§€λ₯Ό ν™•μΈν•˜λŠ” 일을 ν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€. μ—Όμƒ‰μ²΄λŠ” μ•ŒνŒŒλ²³ λŒ€λ¬Έμž (A, B, C, ..., Z)둜만 이루어진 λ¬Έμžμ—΄μ΄λ‹€. μƒκ·Όμ΄λŠ” 각 염색체가 λ‹€μŒκ³Ό 같은 κ·œμΉ™μ„ λ§Œμ‘±ν•˜λŠ”μ§€ 검사해야 ν•©λ‹ˆλ‹€.

  • λ¬Έμžμ—΄μ€ {A, B, C, D, E, F} 쀑 0개 λ˜λŠ” 1개둜 μ‹œμž‘ν•΄μ•Ό ν•œλ‹€.
  • κ·Έ λ‹€μŒμ—λŠ” Aκ°€ ν•˜λ‚˜ λ˜λŠ” κ·Έ 이상 μžˆμ–΄μ•Ό ν•œλ‹€.
  • κ·Έ λ‹€μŒμ—λŠ” Fκ°€ ν•˜λ‚˜ λ˜λŠ” κ·Έ 이상 μžˆμ–΄μ•Ό ν•œλ‹€.
  • κ·Έ λ‹€μŒμ—λŠ” Cκ°€ ν•˜λ‚˜ λ˜λŠ” κ·Έ 이상 μžˆμ–΄μ•Ό ν•œλ‹€.
  • κ·Έ λ‹€μŒμ—λŠ” {A, B, C, D, E, F} 쀑 0개 λ˜λŠ” 1κ°œκ°€ 있으며, 더 μ΄μƒμ˜ λ¬ΈμžλŠ” μ—†μ–΄μ•Ό ν•œλ‹€.


    λ¬Έμžμ—΄μ΄ μ£Όμ–΄μ‘Œμ„ λ•Œ, μœ„μ˜ κ·œμΉ™μ„ λ§Œμ‘±ν•˜λŠ”μ§€ κ΅¬ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜μ„Έμš”.

🚩 Example Output

Good
Infected!
Infected!
Infected!
Infected!
Infected!
Good
Good
Good
Good
const words = [
  '15',
  'AFC',
  'AAFC',
  'AAAFFCC',
  'AAFCC',
  'BAFC',
  'QWEDFGHJMNB',
  'DFAFCB',
  'ABCDEFC',
  'DADC'
];

const regexp = /^[A-F]?A+F+C+[A-F]?$/;

words.forEach(item => {
  if(item.match(regexp))
    console.log('Infected!');
  else
    console.log('Good');
});

🧩 map, slice

πŸ’β€ arr λ°°μ—΄μ—λŠ” 숫자 뒀에 λ‹¨μœ„ λ¬Έμžκ°€ λΆ™κ±°λ‚˜ 숫자 μ•žμ— 특수 λ¬Έμžκ°€ 1개 λΆ™λŠ” ν˜•νƒœμ˜ λ¬Έμžμ—΄λ“€μ΄ λ‹΄κ²¨μžˆμŠ΅λ‹ˆλ‹€. ν•΄λ‹Ή κ°’λ“€μ˜ μ•ž λ˜λŠ” 뒀에 μœ„μΉ˜ν•œ 문자λ₯Ό μ œκ±°ν•˜κ³  숫자둜 ν˜•λ³€ν™˜ν•œ 값듀이 λ‹΄κΈ΄ μƒˆλ‘œμš΄ 배열을 λ°˜ν™˜ν•˜λŠ” removeChar ν•¨μˆ˜λ₯Ό μž‘μ„±ν•˜μ„Έμš”.

🚩 Example Output

[ 1080, 100, 200, 60, 6, -15 ]
let arr = ["1080px", "$100", "+200", "60kg", "6m", "-15"];
console.log(removeChar(arr));

function removeChar(arr){
    return arr.map(item => parseInt(item) || +item.slice(1));
}

🧩 split, reverse, join

πŸ’β€ μ•žμœΌλ‘œ 읽어도 거꾸둜 읽어도 λ˜‘κ°™μ€ λ¬ΈμžμΈμ§€ νŒλ³„ν•˜λŠ” palindrom ν•¨μˆ˜λ₯Ό λ§Œλ“œμ„Έμš”.

🚩 Example Output

true
true
true
true
true
false
const list = ['기러기', 'ν† λ§ˆν† ', 'μŠ€μœ„μŠ€', '인도인', '별λ˜₯별', 'μš°λ³„λ¦Ό'];

list.forEach(item => console.log(palindrom(item)));

function palindrom(str) {
  return str === str.split('').reverse().join('')
}

πŸ‘€ DOM

🧩 클릭 μ‹œ, 색상 λ³€κ²½ν•˜κΈ°

πŸ’β€ input type="color" νƒœκ·Έλ‘œ 색상 선택 ν›„ λ³€κ²½ λ²„νŠΌμ„ ν΄λ¦­ν•˜λ©΄ ν•˜λ‹¨ div의 색상이 λ³€κ²½λ˜λ„λ‘ λ§Œλ“œμ„Έμš”.

🚩 Example Output
[이미지]

<div id="div1" class="area"></div>

<input type="color" id="selectColor">
<button onclick="colorChange();">λ³€κ²½</button>
function colorChange() {
	const $area = document.getElementById('div1');
	const $color = document.getElementById('selectColor');

	$area.style.backgroundColor = $color.value;
};

🧩 클릭 μ‹œ, 크기 μ‘°μ ˆν•˜κΈ°

πŸ’β€ λ²„νŠΌ 클릭 μ‹œ ν•˜λ‹¨ div의 크기가 쑰절 λ˜λ„λ‘ λ§Œλ“œμ„Έμš”.

🚩 Example Output
[이미지]

<div id="div2" class="area"></div>
<button onclick="halfSize();">50x50</button>
<button onclick="defaultSize();">원본(100x100)</button>
<button onclick="doubleSize();">200x200</button>
function halfSize() {
    const $area = document.getElementById('div2');
    $area.style.width = '50px';
    $area.style.height = '50px';
};
function defaultSize() {
    const $area = document.getElementById('div2');
    $area.style.width = '100px';
    $area.style.height = '100px';
}
function doubleSize() {
    const $area = document.getElementById('div2');
    $area.style.width = '200px';
    $area.style.height = '200px';
}

🧩 계산기 λ§Œλ“€κΈ°

πŸ’β€ 첫 번째 κ°’κ³Ό 두 번째 값을 μž…λ ₯ ν›„ μ—°μ‚°μž λ²„νŠΌ 클릭 μ‹œ λ™μž‘ν•˜λŠ” calculator ν•¨μˆ˜λ₯Ό λ§Œλ“œμ„Έμš”. ν•¨μˆ˜μ˜ λ§€κ°œλ³€μˆ˜λ‘œ μ—°μ‚°μž λ²„νŠΌμ΄ 가지고 μžˆλŠ” value 값이 μ „λ‹¬λ©λ‹ˆλ‹€.

🚩 Example Output
[이미지]

첫 번째 κ°’ : <input id="num1">
두 번째 κ°’ : <input id="num2">
<input type="button" value="+" onclick="calculator(this.value);">
<input type="button" value="-" onclick="calculator(this.value);">
<input type="button" value="x" onclick="calculator(this.value);">
<input type="button" value="/" onclick="calculator(this.value);">
<input type="button" value="%" onclick="calculator(this.value);">
계산 κ²°κ³Ό : <span id="calc"></span>
function calculator(value) {
    const $calc = document.getElementById('calc');

    switch(value){
        case '+' : result = Number(num1.value) + Number(num2.value); break;
        case '-' : result = Number(num1.value) - Number(num2.value); break;
        case 'x' : result = Number(num1.value) * Number(num2.value); break;
        case '/' : result = Number(num1.value) / Number(num2.value); break;
        case '%' : result = Number(num1.value) % Number(num2.value); break;
    }
    $calc.innerHTML = result;
}

πŸ’‘ Another Solution

function calculator(value) {
    let su1 = Number(document.getElementById("num1").value);
    let su2 = Number(document.getElementById("num2").value);
    let result = 0;
    switch (value) {
        case "+": result = su1 + su2; break;
        case "-": result = su1 - su2; break;
        case "x": result = su1 * su2; break;
        case "/": result = su1 / su2; break;
        case "%": result = su1 % su2; break;
	}
	document.getElementById("calc").textContent = result;
}

🧩 λͺ©λ‘ μ‚­μ œ, μƒμ„±ν•˜κΈ°

1) λͺ©λ‘ μ‚­μ œ

πŸ’β€ λ²„νŠΌ 클릭 μ‹œ μ•„λž˜ ul νƒœκ·Έ(id:list)의 ν•˜μœ„ νƒœκ·Έ(li)λ₯Ό λͺ¨λ‘ μ‚­μ œν•˜λŠ” deleteList ν•¨μˆ˜λ₯Ό λ§Œλ“œμ„Έμš”.

🚩 Example Output
[이미지]

<button onclick="deleteList();">λͺ©λ‘ μ‚­μ œ</button>
<ul id="list">
    <li>의λ₯˜</li>
    <li>μž‘ν™”</li>
    <li>κ°€μ „</li>
    <li>가ꡬ</li>
    <li>μ‹ν’ˆ</li>
    <li>λ ˆμ €</li>
    <li>μ—¬κ°€</li>
    <li>λ„μ„œ</li>
</ul>
function deleteList() {
    const $list = document.getElementById('list');
    $list.innerHTML = "";
}

2) λͺ©λ‘ 생성

πŸ’β€ λ²„νŠΌ 클릭 μ‹œ "μΆ”κ°€ν•  λͺ©λ‘μ„ μž…λ ₯ν•˜μ„Έμš”"λΌλŠ” prompt 창을 λ„μš°κ³  μž…λ ₯ 받은 값을 λ‚΄λΆ€ ν…μŠ€νŠΈλ‘œ ν•˜μ—¬ λ™μ μœΌλ‘œ li μš”μ†Œ 생성 ν›„ μœ„ ul νƒœκ·Έ(id:list)의 ν•˜μœ„ νƒœκ·Έλ‘œ μΆ”κ°€ν•©λ‹ˆλ‹€.
μž…λ ₯ν•˜μ§€ μ•Šκ³  μ·¨μ†Œ ν–ˆμ„ μ‹œμ—λŠ” μΆ”κ°€ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

🚩 Example Output
[이미지]

<button onclick="createList();">λͺ©λ‘ 생성</button>
function createList(){
    let content = prompt('μΆ”κ°€ν•  λͺ©λ‘μ„ μž…λ ₯ν•˜μ„Έμš”');
    const $list = document.getElementById('list');
    const $li = document.createElement('li');

    if(!content==""){
        $li.textContent = content;
        $list.appendChild($li);
	}
};

🧩 appendChild

πŸ’β€ μ™Όμͺ½μœΌλ‘œ λ²„νŠΌ 클릭 μ‹œ ν•˜λ‹¨μ˜ first, second, third divκ°€ ν•œ μΉΈμ”© μ™Όμͺ½μœΌλ‘œ μ΄λ™ν•˜κ²Œ ν•˜λŠ” left ν•¨μˆ˜λ₯Ό μž‘μ„±ν•˜μ„Έμš”.

  • ex)
    first - second - third 인 μƒνƒœμ—μ„œ left 1번 ν΄λ¦­ν•˜λ©΄ second - third - first둜 λ³€κ²½
    left ν•œ 번 더 ν΄λ¦­ν•˜λ©΄ third - first - second 둜 λ³€κ²½

🚩 Example Output
[이미지]

<button onclick="left();">μ™Όμͺ½μœΌλ‘œ</button>
<div id="area">
    <div class="first">first</div>
    <div class="second">second</div>
    <div class="third">third</div>
</div>
function left(){
	const $area = document.getElementById("area");
	$area.appendChild($area.firstElementChild);
}

πŸ‘€ Event

🧩 lastElementChild

πŸ’β€ μΆ”κ°€ν•˜κΈ° λ²„νŠΌμ„ ν•œ 번 ν΄λ¦­ν•˜λ©΄ κ°€λ‘œ, μ„Έλ‘œ 100px, 1px의 직선 검은 ν…Œλ‘λ¦¬λ₯Ό 가진 빨간색 divλ₯Ό area1 내뢀에 μΆ”κ°€ν•˜κ³  ν•œ 번 더 ν΄λ¦­ν•˜λ©΄ 같은 μŠ€νƒ€μΌμ˜ λ…Έλž€μƒ‰ divλ₯Ό area1 내뢀에 μΆ”κ°€ν•˜μ„Έμš”. μ‚­μ œν•˜κΈ° λ²„νŠΌμ„ λˆ„λ₯΄λ©΄ λ§ˆμ§€λ§‰μ— μΆ”κ°€ 된 divλ₯Ό μ‚­μ œν•©λ‹ˆλ‹€. divλŠ” 수직이 μ•„λ‹Œ μˆ˜ν‰μœΌλ‘œ μΆ”κ°€λ˜μ–΄μ•Ό ν•˜λ©° μ‚­μ œ 된 div 이후에 μΆ”κ°€ 될 λ•Œλ„ 빨간색과 λ…Έλž€μƒ‰ divκ°€ λ²ˆκ°ˆμ•„κ°€λ©° μΆ”κ°€ λ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€.

🚩 Example Output
[이미지]

<button id="add">μΆ”κ°€ν•˜κΈ°</button>
<button id="remove">μ‚­μ œν•˜κΈ°</button>
<div id="area1" class="area"></div>
document.getElementById("add").addEventListener('click', function () {

	const $area1 = document.getElementById("area1");
 	const $newDiv = document.createElement("div");

  	$newDiv.style.width = "100px";
  	$newDiv.style.height = "100px";
    $newDiv.style.border = "1px solid black";
    $newDiv.style.display = "inline-block";

    if (!$area1.lastElementChild || $area1.lastElementChild.style.backgroundColor != "red") {
      $newDiv.style.backgroundColor = "red";
    } else {
      $newDiv.style.backgroundColor = "yellow";
    }

    $area1.appendChild($newDiv);
});

    document.getElementById("remove").addEventListener('click', function () {
      const $area1 = document.getElementById("area1");
      if ($area1.lastElementChild)
        $area1.removeChild($area1.lastElementChild);
});

🧩 예금 이자 계산기 λ§Œλ“€κΈ°

πŸ’β€ μ˜ˆμΉ˜κΈˆμ•‘, μ˜ˆμΉ˜κΈ°κ°„, μ—°μ΄μžμœ¨ 값이 λ³€κ²½ 될 λ•Œλ§ˆλ‹€ 계산 된 κ²°κ³Όλ₯Ό μ›κΈˆκ³Ό λ§ŒκΈ°μ§€κΈ‰κΈˆμ•‘μœΌλ‘œ ν‘œκΈ°ν•©λ‹ˆλ‹€.

🚩 Example Output
[이미지]

<form name="calculator">
  <table>
    <tr>
      <td>μ˜ˆμΉ˜κΈˆμ•‘</td>
      <td>
        <input name="money" type="number" value="10000" required>
      </td>
    </tr>
    <tr>
      <td>μ˜ˆμΉ˜κΈ°κ°„</td>
      <td>
        <select name="months">
          <option value="3">3 (μ΅œλ‹¨ μ˜ˆμΉ˜κΈ°κ°„)</option>
          <option value="6">6 (λ°˜λ…„)</option>
          <option value="12" selected>12 (1λ…„)</option>
          <option value="18">18 (1.5λ…„)</option>
          <option value="24">24 (2λ…„)</option>
          <option value="30">30 (2.5λ…„)</option>
          <option value="36">36 (3λ…„)</option>
          <option value="60">60 (5λ…„)</option>
        </select>
      </td>
    </tr>
    <tr>
      <td>μ—°μ΄μžμœ¨</td>
      <td>
        <input name="interest" type="number" value="5" required>
      </td>
    </tr>
  </table>
</form>
μ›κΈˆ : <span id="money-before">10000</span>
λ§ŒκΈ°μ§€κΈ‰κΈˆμ•‘ : <span id="money-after">10500</span>
// 폼 μ–»κΈ°
const $form = document.forms.calculator;

// 3개 μž…λ ₯ 양식에 κ³„μ‚°μš© ν•¨μˆ˜ 이벀트 κ±ΈκΈ°
$form.money.oninput = calculate;
$form.months.oninput = calculate;
$form.interest.oninput = calculate;

function calculate() {

	const $form = document.forms.calculator;

    // μ˜ˆμΉ˜κΈˆμ•‘ : 문자 -> 숫자둜 ν˜•λ³€ν™˜
    let initial = +$form.money.value;
    if (!initial) return;

    // 예치 κΈ°κ°„ : 1λ…„ 기쀀을 μœ„ν•΄ 12둜 λ‚˜λˆ”
    let years = $form.months.value / 12;
    if (!years) return;

    // μ—°μ΄μžμœ¨ : νΌμ„ΌνŠΈμ΄λ―€λ‘œ 0.01을 곱함
    let interest = $form.interest.value * 0.01;
    if (!interest) return;

    // 반올림 처리 (μ˜ˆμΉ˜κΈˆμ•‘ * (1 + μ—°μ΄μžμœ¨ * 예치 κΈ°κ°„(λ…„)))
    let result = Math.round(initial * (1 + interest * years));

    // μ›κΈˆκ³Ό λ§ŒκΈ°μ§€κΈ‰κΈˆμ•‘ μž…λ ₯
    document.getElementById('money-before').textContent = $form.money.value;
    document.getElementById('money-after').textContent = result;
}

// λ¬Έμ„œ λ‘œλ“œ ν›„ 1번 μžλ™ μ—°μ‚°ν•΄μ„œ κ°’ μ„€μ •
calculate();

🧩 blur, focus

πŸ’β€ divλ₯Ό ν΄λ¦­ν•˜λ©΄ textarea둜 변경이 되고 κ·Έ μ•ˆμ—μ„œ 값을 μž…λ ₯ν•œ λ’€ Enterλ₯Ό λˆ„λ₯΄κ±°λ‚˜ blur μ΄λ²€νŠΈκ°€ λ°œμƒν•˜λ©΄ κ²°κ³Όλ₯Ό div μ•ˆμ— μ €μž₯ν•©λ‹ˆλ‹€.

  • HTML을 적으면 νƒœκ·Έλ‘œ κΈ°λŠ₯
  • μ°Έκ³  : textarea νƒœκ·Έλ₯Ό λ§Œλ“€λ©΄ editμ΄λΌλŠ” 클래슀λͺ…을 λΆ€μ—¬ (CSS 섀정이 있음)
  • node.replaceWith(λ…Έλ“œλ‚˜ λ¬Έμžμ—΄) λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•΄λ³΄κΈ°

🚩 Example Output
[이미지]

<div id="view" class="view">μ—¬κΈ°λ₯Ό ν΄λ¦­ν•΄μ„œ λ‚΄μš©μ„ μž…λ ₯ν•˜μ„Έμš”.</div>
let $area = null;
let $view = document.getElementById('view');

$view.onclick = editStart;

function editStart() {
	$area = document.createElement('textarea');
    $area.className = 'edit';
    $area.value = $view.innerHTML;

    $area.onkeydown = function (event) {
        if (event.key == 'Enter') {
          this.blur();
        }
    };

    $area.onblur = editEnd;

    $view.replaceWith($area);
    $area.focus();
}

function editEnd() {
    $view.innerHTML = $area.value;
    $area.replaceWith($view);
}

πŸ‘€ Timer & BOM

🧩 setInterval, clearInterval

πŸ’β€ μ‹œμž‘ λ²„νŠΌμ„ λˆ„λ₯΄λ©΄ hh:mm:ss의 곡간에 ν˜„μž¬ μ‹œκ°„μ΄ 보여지고 멈좀 λ²„νŠΌμ„ λˆ„λ₯΄λ©΄ λ‹€μ‹œ hh:mm:ss둜 λ³΄μ—¬μ§€κ²Œ ν•˜λŠ” start, stop ν•¨μˆ˜λ₯Ό μž‘μ„±ν•˜μ„Έμš”. 단, ν•œμžλ¦¬ μˆ«μžλŠ” μ•žμ— 0을 λΆ™μ—¬μ„œ λ‘μžλ¦¬λ‘œ ν‘œν˜„ν•©λ‹ˆλ‹€.

🚩 Example Output
[이미지]

<button onclick="start();">μ‹œμž‘</button>
<button onclick="stop();">멈좀</button>
<div id="clock">
	<span class="hour">hh</span>:<span class="min">mm</span>:<span class="sec">ss</span>
</div>
const $clock = document.getElementById('clock');
const $hour = document.getElementsByClassName('hour');
const $min = document.getElementsByClassName('min');
const $sec = document.getElementsByClassName('sec');
        
function start(){
	const date = new Date();
	const hour = date.getHours();
	const min = date.getMinutes();
	const sec = date.getSeconds();
	$clock.innerHTML = `${$hour.innerHTML = hour < 10 ? `0${hour}` : hour}:${$min.innerHTML = min < 10 ? `0${min}` : min}:${$sec.innerHTML = sec < 10 ? `0${sec}` : sec}`
            
	const timerId = setInterval(start, 1000);
}
        
function stop() {
	location.reload();
}

πŸ’‘ Another Solution

let timer;
const clock = document.querySelector("#clock");

function start(){
	if(!timer){
		timer = setInterval(update, 1000);
		update();
	}
}

function stop(){
    clearInterval(timer);
    timer = null;
    clock.children[0].textContent = 'hh';
    clock.children[1].textContent = 'mm';
    clock.children[2].textContent = 'ss';
}

function update(){
    let date = new Date();
    let hour = date.getHours();
    let min = date.getMinutes();
    let sec = date.getSeconds();
    clock.children[0].textContent = hour < 10 ? '0' + hour : hour;
    clock.children[1].textContent = min < 10 ? '0' + min : min;
    clock.children[2].textContent = sec < 10 ? '0' + sec : sec;
}

🧩 μž…λ ₯받은 값을 배열에 μ €μž₯ν•˜κ³  ν•©μ‚°ν•˜κΈ°

πŸ’β€ μ•„λž˜μ˜ 쑰건에 λ§žλŠ” sum ν•¨μˆ˜λ₯Ό μž‘μ„±ν•©λ‹ˆλ‹€. prompt둜 μ‚¬μš©μžμ—κ²Œ 숫자 μž…λ ₯을 반볡 μš”μ²­ν•œ ν›„, μž…λ ₯받은 값듀을 배열에 μ €μž₯ν•©λ‹ˆλ‹€. μˆ«μžκ°€ μ•„λ‹Œ κ°’ ν˜Ήμ€ 빈 λ¬Έμžμ—΄μ„ μž…λ ₯ν•˜κ±°λ‚˜ μ·¨μ†Œ λ²„νŠΌμ„ λˆ„λ₯΄λ©΄ prompt 창의 λ°˜λ³΅μ„ λ©ˆμΆ”κ³  배열에 λ‹΄κΈ΄ 숫자의 합계λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
(단, 숫자 0은 μœ νš¨ν•œ μž…λ ₯으둜 κ°„μ£Όν•©λ‹ˆλ‹€.)

🚩 Example Output
[이미지]

function sum() {

    let numbers = [];

    while (true) {
        let value = prompt("숫자λ₯Ό μž…λ ₯ν•΄ μ£Όμ„Έμš”.", 0);

        if (!value || isNaN(value)) break;
        numbers.push(Number(value));
    }

    let sum = 0;
    for (let key in numbers) {
        sum += numbers[key];
    }
    return sum;
}
console.log("합계 : " + sum());

🧩 prompt, alert

πŸ’β€ κ°’ μΆ”κ°€ λ²„νŠΌμ„ λˆŒλ €μ„ λ•Œ λœ¨λŠ” prompt에 μž…λ ₯ 된 값을 배열에 μˆœμ„œλŒ€λ‘œ μ €μž₯ν•©λ‹ˆλ‹€. 단, μ·¨μ†Œ 및 κ°’ μž…λ ₯ 없이 확인을 λˆŒλ €μ„ κ²½μš°λŠ” μ €μž₯ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. κ°’ 좜λ ₯ λ²„νŠΌμ„ λˆ„λ₯΄λ©΄ μ§€κΈˆκΉŒμ§€ μž…λ ₯ 된 값을 alert둜 좜λ ₯ν•©λ‹ˆλ‹€. 단, 아직 μž…λ ₯ 된 값이 μ—†λŠ” μƒνƒœμ—μ„œ λ²„νŠΌμ΄ 눌리면 '값이 λ¨Όμ € μž…λ ₯ λ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€.'λ₯Ό 좜λ ₯ν•©λ‹ˆλ‹€. κ°’ μ‚­μ œ λ²„νŠΌμ„ λˆ„λ₯΄λ©΄ μ§€κΈˆκΉŒμ§€ μž…λ ₯ λ˜μ—ˆλ˜ λ°°μ—΄μ˜ 값을 λͺ¨λ‘ μ œκ±°ν•œ λ’€ '값이 λͺ¨λ‘ μ‚­μ œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.'λ₯Ό 좜λ ₯ν•©λ‹ˆλ‹€.

🚩 Example Output
[이미지]

<button onclick="input(prompt('값을 μž…λ ₯ν•˜μ„Έμš”'));">κ°’ μΆ”κ°€</button>
<button onclick="print();">κ°’ 좜λ ₯</button>
<button onclick="reset();">κ°’ μ‚­μ œ</button>
let data = [];

function input(value) {
    if (value)
        data.push(value);
}

function print() {
    if (data.length != 0)
        alert(data);
    else
        alert('값이 λ¨Όμ € μž…λ ₯ λ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€.');
}

function reset() {
    data.length = 0;
    alert('값이 λͺ¨λ‘ μ‚­μ œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.');
}
profile
Tiny little habits make me
post-custom-banner

0개의 λŒ“κΈ€