Recursion

1. ์žฌ๊ท€ํ•จ์ˆ˜๋ž€?

  • ์ž๊ธฐ ์ž์‹ ์„ ํ˜ธ์ถœํ•˜๋Š” ํ•จ์ˆ˜

  • ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์ ํ•ฉํ•œ ๋•Œ

    • ์ฃผ์–ด์ง„ ๋ฌธ์ œ๋ฅผ ๋น„์Šทํ•œ ๊ตฌ์กฐ์˜ ๋” ์ž‘์€ ๋ฌธ์ œ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ

    • ์ค‘์ฒฉ๋œ ๋ฐ˜๋ณต๋ฌธ์ด ๋งŽ๊ฑฐ๋‚˜ ๋ฐ˜๋ณต๋ฌธ์˜ ์ค‘์ฒฉ ํšŸ์ˆ˜๋ฅผ ์˜ˆ์ธกํ•˜๊ธฐ ์–ด๋ ค์šด ๊ฒฝ์šฐ

  • ์˜ˆ์‹œ ์ฝ”๋“œ

    // ๋นˆ ๋ฐฐ์—ด์„ ๋ฐ›์•˜์„ ๋•Œ 0์„ ๋ฆฌํ„ดํ•˜๋Š” ์กฐ๊ฑด๋ฌธ
    // ๊ฐ€์žฅ ์ž‘์€ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋Š” ์ฝ”๋“œ & ์žฌ๊ท€๋ฅผ ๋ฉˆ์ถ”๋Š” ์ฝ”๋“œ
    function arrSum(arr) {
      if(arr.length === 0) {
          return 0
      }
      // ๋ฐฐ์—ด์˜ ์ฒซ ์š”์†Œ + ๋‚˜๋จธ์ง€ ์š”์†Œ๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด์„ ๋ฐ›๋Š” arrSum ํ•จ์ˆ˜
      // ์žฌ๊ท€๋ฅผ ํ†ตํ•ด ๋ฌธ์ œ๋ฅผ ์ž‘๊ฒŒ ์ชผ๊ฐœ ๋‚˜๊ฐ€๋Š” ์ฝ”๋“œ
      // arrSum([5]) === 5 + arrSum([]) === 5 + 0 === 5;
      // arrSum([4, 5]) === 4 + arrSum([5]) === 4 + 5 === 9;
      return arr.shift() + arrSum(arr)
    }

2. ์žฌ๊ท€์  ์‚ฌ๊ณ 

1. ์žฌ๊ท€ ํ•จ์ˆ˜์˜ ์ž…๋ ฅ๊ฐ’๊ณผ ์ถœ๋ ฅ๊ฐ’ ์ •์˜ํ•˜๊ธฐ

  • ๊ฐ€์žฅ ์ถ”์ƒ์  or ๊ฐ€์žฅ ๋‹จ์ˆœํ•˜๊ฒŒ ์ •์˜ํ•˜๊ธฐ

2. ๋ฌธ์ œ๋ฅผ ์ชผ๊ฐœ๊ณ  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋‚˜๋ˆ„๊ธฐ

  • ์ž…๋ ฅ๊ฐ’์ด๋‚˜ ๋ฌธ์ œ์˜ ์ˆœ์„œ/ํฌ๊ธฐ์— ๋”ฐ๋ผ ์ชผ๊ฐœ๊ธฐ

3. ๋‹จ์ˆœํ•œ ๋ฌธ์ œ ํ•ด๊ฒฐํ•˜๊ธฐ

  • ๊ฐ€์žฅ ์‰ฌ์šด ๋ฌธ์ œ๋ถ€ํ„ฐ ํ•ด๊ฒฐ โ†’ ์žฌ๊ท€์˜ ๊ธฐ์ดˆ: ์ด๋Š” ์ถ”ํ›„ ์žฌ๊ท€์˜ ํƒˆ์ถœ ์กฐ๊ฑด์„ ๊ตฌ์„ฑ

  • ํƒˆ์ถœ ์กฐ๊ฑด์ด ์—†๋‹ค๋ฉด ์žฌ๊ท€ ํ•จ์ˆ˜๋Š” ์ž์‹ ์„ ๋์—†์ด ํ˜ธ์ถœํ•˜๋ฏ€๋กœ ๋ฌธ์ œ๋ฅผ ์ตœ๋Œ€ํ•œ ์ž‘๊ฒŒ ์ชผ๊ฐœ๊ธฐ

4. ๋ณต์žกํ•œ ๋ฌธ์ œ ํ•ด๊ฒฐํ•˜๊ธฐ

  • ๋‚จ์•„์žˆ๋Š” ๋ณต์žกํ•œ ๋ฌธ์ œ ํ•ด๊ฒฐ

5. ์ฝ”๋“œ ๊ตฌํ˜„ํ•˜๊ธฐ

function recursive (input1, input2, ...) {
    // base case: ๋ฌธ์ œ๋ฅผ ๋”์ด์ƒ ์ชผ๊ฐค ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ
    if (๋ฌธ์ œ๋ฅผ ๋”์ด์ƒ ์ชผ๊ฐค ์ˆ˜ ์—†์„ ๊ฒฝ์šฐ) {
        return ๋‹จ์ˆœํ•œ ๋ฌธ์ œ์˜ ํ•ด๋‹ต;
    }

    // recursive case: ๊ทธ๋ ‡์ง€ ์•Š์€ ๊ฒฝ์šฐ
    return ๋” ์ž‘์€ ๋ฌธ์ œ๋กœ ์ƒˆ๋กญ๊ฒŒ ์ •์˜๋œ ๋ฌธ์ œ
}

3.JSON.stringigy

1. JSON์˜ ํƒ„์ƒ ๋ฐฐ๊ฒฝ

  • JSON์€ JavaScript Object Notation๋กœ์„œ, ์„œ๋กœ ๋‹ค๋ฅธ ํ”„๋กœ๊ทธ๋žจ ์‚ฌ์ด์—์„œ ๋ฐ์ดํ„ฐ ๊ตํ™˜์„ ์œ„ํ•ด ๋งŒ๋“ค์–ด์ง„ ๊ฐ์ฒด ํ˜•ํƒœ์˜ ํฌ๋งท

2. ๋ฉ”์†Œ๋“œ

JSON.stringify: ๊ฐ์ฒด โ†’ JSON๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๋ฉ”์†Œ๋“œ

// message ๊ฐ์ฒด๋ฅผ JSON์œผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๋ฉ”์†Œ๋“œ JSON.stringify

let transferableMessage = JSON.stringify(message)

console.log(transferableMessage)
// `{"sender":"Ella","receiver":"Chloe","message":"Hi, Chloe.","createdAt":"2023-04-12 10:10:10"}`

console.log(typeof(transferableMessage)) // `string`

JSON.parse: JSON โ†’ ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๋ฉ”์†Œ๋“œ

// ์ง๋ ฌํ™”๋œ JSON์— ๋ฉ”์†Œ๋“œ JSON.parse๋ฅผ ์ ์šฉํ•ด ๋‹ค์‹œ ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜: ์—ญ์งˆ๋ ฌํ™”

let packet = `{"sender":"Ella","receiver":"Chloe","message":"Hi, Chloe.","createdAt":"2023-04-12 10:10:10"}`
let obj = JSON.parse(packet)

console.log(obj)
/*
 * {
 * sender: "Ella",
 * receiver: "Chloe",
 * message: "Hi, Chloe.",
 * createdAt: "2023-04-12 10:10:10"
 * }
 */

console.log(typeof(obj)) // `object`

3. JSON ๊ธฐ๋ณธ ๊ทœ์น™

Last updated