[TIL] 24.09.19 THU

GDORI·2024년 9월 19일
0

TIL

목록 보기
46/79
post-thumbnail

[ 오늘 푼 SQL 코드카타 ]

오늘은 챌린지반 데이라 깔쌈하게 SQL 코드카타 문제 하나 풀어보았다.
영어라 좀 당황했는데 흐름을 느껴 풀었다

문제

문제사이트

풀이

주어진 테이블에는 동물 품종들의 position 과 rating이 있다
이를 이용하여 quality와 poor_query_percentage를 계산하여 소수점 2자리수까지 반올림하여 출력하면 되는 문제이다.

quality는 각 품종마다 rating / position을 한 값에서 평균을 낸 것이고, poor_query_percentage는 rating이 3 미만인 품종의 평균이다.

sql 코드

SELECT query_name, 
       ROUND(AVG(rating / position), 2) AS quality, 
       ROUND(AVG(rating < 3) * 100, 2) AS poor_query_percentage
FROM Queries
GROUP BY query_name;

결과

오랜만에 JS 복습

Docs 페이지에 예제가 있길래 JS 복습할 겸 풀어보았다.

문자열 길이

// 입력받은 문자열의 길이를 구해서 result 값이 아래와 같이 출력되도록 함수를 완성해 보세요.

function getLengthOfString(str) {
	// 이 부분에 코드를 작성하세요.
  return [...str].length
}

const result = getLengthOfString("abcde");
console.log(result); // 출력 결과: 5

문자열 자르기

// 입력받은 문자열을 잘라서 result 값이 아래와 같이 출력되도록 함수를 완성해 보세요.
// 메소드는 slice 를 이용해 보세요.

function getToken(str) {
	// 이 부분에 코드를 작성하세요.
  return str.slice(7);
}

const result = getToken("Bearer a012345");
console.log(result); // 출력 결과: 'a012345'

문자열 대체

// 아래 결과와 같이 출력되도록 newStr에 들어갈 코드를 작성해 보세요.

const str = "I like coffee but I don't like coffee shop.";

const newStr = str.replace("coffee","tea")  //  replace 메소드를 이용하여 이 부분을 완성해 보세요.
// replaceAll을 사용하면 I like tea but I don't like tea shop 이 출력된다.

console.log(newStr);
// 출력 결과: "I like tea but I don't like coffee shop."

문자열 분할

// 아래 결과와 같이 출력되도록 newStr에 들어갈 코드를 작성해 보세요.

const str = "green/red/yellow/blue/white";

const splittedArr =  str.split("/");// split 메소드를 이용하여 이 부분을 작성해 보세요.

console.log(splittedArr);
// 출력 결과: ["green", "red", "yellow", "blue", "white"]

명시적 형변환 - 숫자 형변환

// 문자열을 입력받아도 result 값이 아래와 같이 출력되도록 함수를 완성해 보세요.
// if문과 typeof 키워드를 이용해야 합니다.

function add(a, b) {
	// 이 부분을 완성해 보세요.
  if(typeof(a) !== 'number')
    a = +a;
  else if(typeof(b) !== 'number')
    b = +b;
  
  return a+b;
}

const result1 = add(5, "5");
const result2 = add("5", 5);

console.log(result1); // 출력 결과: 10
console.log(result2); // 출력 결과: 10

Truthy / Falsy

// 아래 함수는 배열을 입력받아서 배열 요소들 중 truthy한 요소들만 필터링하여 반환합니다.
// Truthy 란 boolean type을 기대하는 문맥에서 true 로 평가되는 값을 의미합니다.
// for문과 if문을 이용하여 작성해 보세요.

function getTruthyArray(arr) {
	const truthyArr = [];
	// 이 부분을 완성해 보세요.
	arr.forEach((data)=>{
    if(data)
      truthyArr.push(data);
  })
	return truthyArr;
}

const result = getTruthyArray( [ -1, 0, "", {}, [], null, undefined, NaN ] );
console.log(result); // 출력 결과: [-1, {}, []]

연산자- 홀수/짝수 구분

// 숫자 배열을 입력받아서 홀수의 값만 합치는 함수를 완성해 보세요.
// result 값이 아래아 같이 출력되어야 합니다.
// for문, if문, %(나머지) 연산자를 사용해 보세요.

function sumOdd(arr) {
	let sum = 0;
	// 이 부분을 완성해 보세요.
	arr.forEach((num)=>{
    if(num%2===1)
      sum += num
  })
	return sum;
}

const result = sumOdd( [1,2,3,4,5 ] );
console.log(result); // 출력 결과: 9

논리연산자 ||

// 아래의 결과와 같이 출력되도록 함수를 완성해 보세요.

function order(item, quantity, price) {
	// item, quantity, price 중 하나라도 입력이 되어 있지 않으면
	// '주문 정보를 모두 입력해주세요' 를 리턴합니다.
	// quantity 수량이 0이하면
	// '수량은 1개 이상 입력해주세요' 를 리턴합니다.
	// 위 두 가지 경우만 아닌 경우에만 아래와 같이 주문 완료 메시지를 출력합니다.
  // 이 부분에 코드를 작성해 보세요.
  if(!item||!quantity||!price)
    return '주문 정보를 모두 입력해주세요.';
  else if(quantity<=0)
    return '수량은 1개 이상 입력해주세요.';
  else
    return `주문이 완료되었습니다. ${item} ${quantity}개를 ${price}에 구매하셨습니다.`;
}

console.log(order('아이폰 12', 2, 1200000));
// 출력 결과: '주문이 완료되었습니다. 아이폰 12 2개를 2400000원에 구매하셨습니다.'

console.log(order('맥북 프로', -1, 2500000));
// 출력 결과: '수량은 1개 이상 입력해주세요'

console.log(order('아이패드 에어', 1, null));
// 출력 결과: '주문 정보를 모두 입력해주세요'

논리연산자 &&

// 전통주 시음회가 있다고 가정합니다. 입장 티켓을 소유하고 나이 19세 이상이어먄 입장이 가능합니다.
// 2가지 조건을 모두 만족하는 지 검사하는 아래 함수를 완성해 보세요.

function checkAgeAndTicket(age, hasTicket) {
	// "Pass" 또는 "Fail" 을 반환해야 합니다.
	return (age >= 19 && hasTicket) ? "Pass" : "Fail";
}

const result1 = checkAgeAndTicket(19, true);
console.log(result1); // "Pass"

const result2 = checkAgeAndTicket(17, true);
console.log(result2); // "Fail"

함수 정의 문법

// 함수 선언문으로 정의한 foo 함수
function foo() {
	console.log("함수 선언문");
}
foo(); // 함수 선언문

// "함수 표현식"을 콘솔로그로 출력하는 foo2 함수 표현식으로 만들어 보세요.
// function 키워드를 사용해 주세요.
const foo2 = function() {
		
}
foo2(); // 함수 표현식

// "화살표 함수"를 콘솔로그로 출력하는 foo3 화살표 함수를 만들어 보세요.
const foo3 = () => console.log("화살표 함수");
foo3(); // 화살표 함수

/* 참고로 화살표 함수 역시 변수에 함수가 할당되는 함수 표현식 입니다. */

객체 및 배열 메소드 응용

// 아래와 같은 결과가 출력되도록 함수를 완성해 보세요.
const db = [
	{
		"id": 7,
		"name": "Jay",
		"age": 33,
		"phone": "010-1212-5678",
		"email": "qwe@gmail.com"
	},
	{
		"id": 10,
		"name": "James",
		"age": 30,
		"phone": "010-1234-5678",
		"email": "abc@gmail.com"
	}
]
	
function handleEdit(id, editingObj) {
	// db에서 id에 해당하는 객체를 찾아서 내용을 바꿉니다.
	// 배열 요소를 찾을 때 배열의 find 또는 findIndex 메소드를 사용해 보세요.
	// Object.assign 을 사용해서 객체의 내용을 수정해 보세요.
	// 여기에 코드를 작성하세요.
	const idx = db.findIndex(element => element.id === id)
  Object.assign(db[idx],editingObj)
}

handleEdit(10, { name: "Paul", age: 35 });

console.log(db);
/*
출력 결과:
[
	{
		"id": 7,
		"name": "Jay",
		"age": 33,
		"phone": "010-1212-5678",
		"email": "qwe@gmail.com"
	},
	{
		"id": 10,
		"name": "Paul",
		"age": 35,
		"phone": "010-1234-5678",
		"email": "abc@gmail.com"
	}
]
*/

배열 메소드 filter

// 아래 결과와 같이 출력되도록 함수를 완성해 보세요.

function getEvenNumbers(arr) {
	// 인자로 받은 숫자를 요소를 갖는 배열에서 짝수만 필터하여 배열로 반환하세요. 
	// 배열의 filter 메소드를 이용하세요.
	// 여기에 코드를 작성하세요.
  return arr.filter(element=>element%2===0)
	
}

const result = getEvenNumbers( [1,2,3,4,5,6,7,8,9,10] );
console.log(result); // [2,4,6,8,10]

for,continue,break

// for문과 continue, break 키워드를 사용하여 아래 결과와 같이 출력되도록 함수를 완성해 보세요.

function countEvenNumbersUpto5(numArr) {
	// numArr 배열을 요소들을 탐색하여 요소가 짝수인 경우 개수를 카운트 해야 합니다.
	// 그러나 개수는 최대 5개까지만 셀 수 있도록 제한합니다.
  let count = 0;
  // 이 부분을 완성해 보세요.
  for(let i=0; i<numArr.length; i++){
    if(numArr[i]%2===0)
      count++;
    else
      continue;
    if(count === 5) break;
  }

  return count;
}

const result1 = countEvenNumbersUpto5( [1,2,3,4,6,8,10,12,13,14,15,16] );
console.log(result1); // 출력 결과: 5

const result2 = countEvenNumbersUpto5( [1,3,5,6,8,10] );
console.log(result2); // 출력 결과: 3

삼항연산자

// 아래와 같이 출력되도록 함수를 완성해 보세요.
// if문 없이 삼항연산자를 사용해 보세요.

function getMessageIfHot(temperature) {
	// temperature 가 26보다 크면 "It's hot!", 작으면 "Its' not hot!"
	// 여기에 코드를 작성하세요.
	return temperature>26 ? "It's hot!" : "It's not hot!"
}

const result = getMessageIfHot(26);
console.log(result); // 출력 결과: 'It's not hot!'

구조분해할당

// 호텔의 예약 확인 시스템의 함수라고 가정합니다.
// 아래 결과와 같이 출력되도록 함수를 완성해 보세요.

function confirmReservation(user) {
	// 여기에 user 객체를 구조 분해 할당 하세요.
	const {name,roomType,firstDate} = user;
	return `${name} 고객님의 ${roomType}룸 입실날짜는 ${firstDate} 입니다.`
}

const userInfo = {
  name: "James",
	roomType: "Deluxe",
	date: "2023-05-30"
}
const result = confirmReservation(userInfo);
console.log(result);
// 출력 결과: 'James 고객님의 Deluxe룸 입실날짜는 2023-05-30 입니다.'

Spread operator

// 아래와 같은 결과가 출력되도록 함수를 완성해 보세요.
const db = [
	{
		"id": 7,
		"name": "Jay",
		"age": 33,
		"phone": "010-1212-5678",
		"email": "qwe@gmail.com"
	},
	{
		"id": 10,
		"name": "James",
		"age": 30,
		"phone": "010-1234-5678",
		"email": "abc@gmail.com"
	}
]
	
function handleEdit(id, editingObj) {
	// db에서 id에 해당하는 객체를 찾아서 내용을 바꿉니다.
	// Object.assign 대신 spread syntax(...)를 사용해야 합니다.
	// 여기에 코드를 작성하세요.
	const idx = db.findIndex(element => element.id === id)
  db[idx] = {...db[idx], ...editingObj}
}

handleEdit(10, { name: "Paul", age: 35 });

console.log(db);
/*
출력 결과:
[
	{
		"id": 7,
		"name": "Jay",
		"age": 33,
		"phone": "010-1212-5678",
		"email": "qwe@gmail.com"
	},
	{
		"id": 10,
		"name": "Paul",
		"age": 35,
		"phone": "010-1234-5678",
		"email": "abc@gmail.com"
	}
]
*/

고차함수

// 고차 함수: 함수를 매개변수로 받거나 리턴하는 함수
// 아래 결과와 같이 출력되도록 고차 함수를 완성해 보세요.

function divideBy(num) {
	return x => x / num;
}

const divideBy100 = divideBy(100);
const result = divideBy100(10);
console.log(result); // 0.1

SET

// 아래 결과와 같이 출력되도록 함수를 완성해 보세요.
// 자료구조 Set 의 인자로 배열을 넣으면 중복요소가 없는 배열을 반환받을 수 있습니다.
// spread syntax 를 사용해 보세요. Set을 배열로 변환할 수 있습니다.

function getNoDuplicates(arr) {
	// 여기에 코드를 작성하세요.
	return [...new Set(arr)]
}

const result = getNoDuplicates([1, 5, 2, 3, 4, 1, 2, 5, 6, 3]);
console.log(result); // 출력 결과: [1, 5, 2, 3, 4, 6]

얕은복사


// 아래 결과와 같이 나오도록 아래 함수를 완성해 보세요.

function shallowCopy(obj) {
	// Object.assign 또는 spread syntax를 이용해 보세요.
	// 여기에 코드를 작성하세요.
  return {...obj}
	
}

const obj = {
  name: 'John',
  age: 30,
  address: {
    city: 'Seoul',
    country: 'South Korea',
		details: ['도로명주소', '지번주소']
  }
};

const shallowCopied = shallowCopy(obj);

console.log( obj === shallowCopied ); // 출력 결과: false
console.log( obj.age === shallowCopied.age) ; // 출력 결과: true
console.log( obj.address === shallowCopied.address ); // 출력 결과: true
console.log( obj.address.city === shallowCopied.address.city ); // 출력 결과: true
console.log( obj.address.details === shallowCopied.address.details ); // 출력 결과: true

깊은복사


// 아래 결과와 같이 나오도록 아래 함수를 완성해 보세요.

function deepCopy(obj) {
	// 모든 depth 까지 재귀적으로 탐색하여 복사한 객체를 return 하세요.
	// if문과 typeof 키워드를 이용해 보세요.
var res = {};
	if (typeof obj === 'object' && obj !== null) {
		for (var idx in obj) {
			res[idx] = deepCopy(obj[idx]);
		}
	} else {
		res = obj;
	}
	return res;
}

const obj = {
  name: 'John',
  age: 30,
  address: {
    city: 'Seoul',
    country: 'South Korea',
		details: ['도로명주소', '지번주소']
  }
};

const deepCopied = deepCopy(obj);
console.log( obj === deepCopied ); // 출력 결과: false
console.log( obj.age === deepCopied.age) ; // 출력 결과: true
console.log( obj.address === deepCopied.address ); // 출력 결과: false
console.log( obj.address.city === deepCopied.address.city ); // 출력 결과: true
console.log( obj.address.details === deepCopied.address.details ); // 출력 결과: false

최대값

// 아래 결과와 같이 출력되도록 함수를 완성해 보세요.
// apply 또는 spread syntax를 이용해 보세요.

function getMaxNumber(arr) {
	// 자바스크립트의 내장 객체인 Math 를 이용하세요.
	// arr 는 숫자로만 이루어진 배열입니다.
	// 여기에 코드를 작성하세요.
	return Math.max(...arr)
}

const result = getMaxNumber( [5,10,3,12,1,9] );
console.log(result); // 출력 결과: 12

SetInterval

// 아래 타이머 함수를 요구사항에 맞게 완성해 보세요.

let count = 0;

const timerId = setInterval(callbackFunc, 1000);

function callbackFunc() {
	// count 가 7이 되면 타이머를 멈추도록 해보세요.
	// 이 부분을 완성해 보세요.	
  count ++;
	console.log(count);
  if(count === 7) clearInterval(timerId);
}
/*
출력 결과:
1
2
3
4
5
6
7
*/

Array map

// 아래 결과와 같이 출력되도록 함수를 완성해 보세요.

function mapArray(arr) {
	// 배열의 map 메소드를 이용해 보세요.
	// 객체 {key: value}의 key가 변수를 참조하려면 [key] 이렇게 대괄호 안에 넣으세요.
  // 여기에 코드를 작성하세요.
   
	return arr.map((data,i)=>({[i]:data}))
}

const result = mapArray( ["a","b","c"] );
console.log(result); // 출력 결과: [{0: 'a'}, {1: 'b'}, {2: 'c'}]

promise

// fetch API는 Response 객체를 Resolving하는 Promise를 반환합니다.
// Response의 body 값에 접근하는 방법은 Response.json() 입니다.
// 아래 결과와 같이 출력되도록 함수를 완성해 보세요.

function fetchAndPrintJson(url) {
  // 매개변수로 받은 url 주소의 데이터를 fetch 받아와서 출력하는 함수를 작성하세요.
  return fetch(url)
  .then((respon)=>{
    return respon.json()
  })
  .then((data)=> {
    console.log(data)
  });
	
}

fetchAndPrintJson('https://jsonplaceholder.typicode.com/posts/1');
/*
출력 결과:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
*/

async/await

// fetch API는 Response 객체를 Resolving하는 Promise를 반환합니다.
// await Promise(result) 는 result 값을 반환해 줍니다.
// 아래 결과와 같이 출력되도록 함수를 완성해 보세요.

async function fetchJson(url) {
  // 여기에 코드를 작성하세요.
  const data = await fetch(url);
  const result = await data.json();
  console.log(result)
  
}

fetchJson('https://jsonplaceholder.typicode.com/posts/1');
/*
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
*/
profile
하루 최소 1시간이라도 공부하자..

0개의 댓글