sungyup's.

javascript_algorithm / 알고리즘 기본 패턴 / 2.7 Recursion-Practice 2

2.7Recursion-Practice 2

재귀 패턴 연습 문제 2

TL;DR

이전 포스팅에서 배운 재귀 알고리즘을 추가적으로 연습해보자.

예시 5: capitalizeWords

Write a recursive function called capitalizeWords. Given an array of strings, capitalize all the letters of the strings in the array.

javascript
function capitalizeWords(array){ if(array.length === 1){ return [array[0].toUpperCase()]; } let res = capitalizeWords(array.slice(0, -1)); res.push(array.slice(array.length - 1)[0].toUpperCase()); return res; }

예시 6: nestedEvenSum

Write a recursive function called nestedEvenSum. Return the sum of all even numbers in an object which may contain nested objects.

javascript
function nestedEvenSum(obj, sum = 0){ for(let key in obj){ if(typeof obj[key] === 'object'){ sum += nestedEvenSum(obj[key]); } else if(typeof obj[key] === 'number' && obj[key] % 2 === 0){ sum += obj[key]; } } return sum; }

예시 7: stringifyNumbers

Write a function called stringifyNumbers which takes in an object and finds all of the values which are numbers and converts them to strings. Recursion would be a great way to solve this!

The exercise intends for you to create a new object with the numbers converted to strings, and not modify the original. Keep the original object unchanged.

javascript
function stringifyNumbers(obj){ const newObj = {}; for(let key in obj){ if(typeof obj[key] === 'number'){ newObj[key] = obj[key].toString(); } else if (typeof obj[key] === 'object' && !Array.isArray(obj[key])){ newObj[key] = stringifyNumbers(obj[key]) } else { newObj[key] = obj[key] } } return newObj; }

예시 8: collectStrings

Write a function called collectStrings which accepts an object and returns an array of all the values in the object that have a typeof string

javascript
function collectStrings(obj){ const stringsArr = []; for(let key in obj){ if(typeof obj[key] === 'string'){ stringsArr.push(obj[key]); } else if(typeof obj[key] === 'object'){ stringsArr = stringsArr.concat(collectStrings[obj[key]]); } } return stringsArr; }

나는 이렇게 풀었다. push 메소드를 쓸 거면 배열을 펼쳐서 넣고, 그렇지 않으면 concat으로 합쳐야 한다.

javascript
function collectStrings(obj){ const collection = []; for(let key in obj){ if(typeof obj[key] === 'object' && !Array.isArray(obj[key])){ collection.push(...collectStrings(obj[key])) } else if(typeof obj[key] === 'string'){ collection.push(obj[key]) } else console.log(obj[key]) } return collection; }