Arrow Function

화살표 함수

화살표 함수는 return 밖에 없는 함수를 줄여서 표현할 수 있는 함수로, 람다식이라고도 부른다.

 

function add(a, b){
	return a + b;
}
console.log(add(1, 4)); // 5

// Arrow Function
const add = (a, b) => {
	return a + b;
}

// 또는 
// const add = (a, b) => a + b;
console.log(add(1, 4)); // 5

 

 

람다식의 표현은 함수의 앞에 매개변수를 괄호로 묶고 화살표 연산자를 사용한 뒤에 함수의 본문을 작성한다.

 

화살표 함수의 특징은 함수명, arguments, this 세 가지가 없다.

 

함수명이 없으므로 익명 함수로 동작하게 된다.

 

Anonymous Function

익명 함수

익명 함수는 이름이 없는 함수로 함수 코드가 변수명에 저장된 형태이다.

 

따라서 변숫값으로 구성된 함수 코드를 다른 변수명에 변수를 대입하듯이 사용되거나 다른 함수의 인수로 전달하는 방식으로 주로 사용된다.

 

const func = function() {
	console.log("Anonymous Function");
};

 

add라는 이름의 변수에 화살표 함수로 만든 이름 없는 익명 함수가 할당된다.

 

이렇게 익명함수는 간단한 표현으로 가독성과 간결함이 좋기 때문에 주로 일회성 작업이나 콜백 함수로 사용된다.

 

One-time Use

일회성 사용

익명 함수는 함수가 특정 작업을 수행한 후 다시 호출될 필요가 없는 경우와 같이 일회성으로 사용되는 경우가 많다.

 

setTimeOut(function() {
	console.log("Time Out");
}, 2000);

 

setTimeOut에 전달된 익명 함수는 2초의 시간 지연 후 한 번만 실행되게 된다.

 

변수나 프로퍼티에 할당 가능

일반적으로 변수나 객체의 프로퍼티에 할당될 수 있다. 이를 사용해서 여러 곳에서 재사용이 가능하다.

 

conse obj = {
	greet : function() {
    	console.log("Hello");
    }
};
obj.greet(); // Hello

 

greet 프로퍼티에 할당된 익명 함수는 객체를 통해서 여러 번 다시 사용이 가능하다.

 

자신을 참조할 수 없음

익명 함수는 이름이 없기 때문에 일반적으로 함수 내부에서 자신을 직접 참조할 수 없다.

 

따라서 재귀 호출과 같이 자신을 호출이 필요한 경우에는 이름이 있는 함수를 사용하는 것이 좋지만 이를 우회하여 표현식에 이름을 명시적으로 붙일 수 있다.

 

const factorial = function f(n) { // 이름 f 명시
	if (n <= 1) return 1;
    return n * f(n - 1);
};
console.log(factorial(5)); // 120

 

f는 함수 표현식의 이름이지만 factorial 변수에 익명 함수처럼 할당되어 내부에서 f를 사용하여 재귀 호출이 가능하다.

 

this 바인딩 없음

익명 함수 중에서도 화살표 함수는 자체적인 this를 가지지 않고 선언된 환경의 this를 상속받는다.

 

하지만 일반적인 익명 함수는 호출 문맥에 따라 this를 설정하는데 this 바인딩이 없기 때문에 화살표 함수의 경우 다르게 동작한다.

 

// anonymous func
const obj = {
  name: "bak",
  regularFunction: function() {
    console.log(this.name);
  }
};
obj.regularFunction(); // bak 

// arrow func
window.name = "global scope";
const obj = {
  name: "bak",
  arrowFunction: () => {
    console.log(this.name);
  }
};
obj.arrowFunction(); // global scope

 

일반적인 익명 함수에서 this는 문맥, 즉 함수가 호출되는 시점과 방식에 따라서 그 객체가 this가 된다.

 

하지만 화살표 함수는 고유한 this 바인딩이 없고 대신에 함수를 정의한 상위 스코프의 this를 상속받게 된다.

 

obj의 메서드로 정의된 것처럼 보이는 화살표 함수는 이러한 바인딩이 없는 특성으로 인해서 상위 스코프의 this를 상속받게 되어 위의 예제의 경우처럼 화살표 함수는 자신이 정의된 시점의 this를 상속받게 된다

 

따라서 this의 객체는 obj가 아닌  전역 객체 this를 가리키게 되고 this.name 은 window.name을 출력하게 된다.

728x90
반응형

this

자바스크립트에서 this는 함수가 호출될 때, 즉 함수의 실행 문맥에 따라 결정되는 특수한 객체이다.

 

 

Global Context

전역 문맥

전역에서 this를 사용할 때 window 또는 global 객체를 가리킨다.

 

console.log(this) // this 는 window or global 객체이다

 

 

Function Context

함수 문맥

일반 함수 내부에서 this는 호출된 문맥에 따라 다르다. 

 

기본적으로 전역 문맥에서 호출된 함수의 this는 전역 객체를 가리키지만 엄격 모드에서는 this가 undefined로 설정된다.

 

"use strict";
function Func(){
	console.log(this);
}

Func(); // undefined

 

 

Method Context

메서드 문맥

객체의 메서드로 호출된 함수에서 this는 그 메서드가 속한 객체를 가리키게 된다.

const myObject = {
	name : "bak",
    say : function() {
    	console.log(this.name);
    }
};

myObject.say(); // bak 출력

 

여기서 this는 myObject 객체가 된다.

728x90
반응형

6번 크로아티아 알파벳

문제

예전에는 운영체제에서 크로아티아 알파벳을 입력할 수가 없었다. 따라서, 다음과 같이 크로아티아 알파벳을 변경해서 입력했다.

 

크로아티아 알파벳 변경
č c=
ć c-
dz=
đ d-
lj lj
nj nj
š s=
ž z=

 

예를 들어, ljes=njak은 크로아티아 알파벳 6개(lj, e, š, nj, a, k)로 이루어져 있다. 단어가 주어졌을 때, 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다. dž는 무조건 하나의 알파벳으로 쓰이고, d와 ž가 분리된 것으로 보지 않는다. lj와 nj도 마찬가지이다. 위 목록에 없는 알파벳은 한 글자씩 센다.

 

입력

첫째 줄에 최대 100글자의 단어가 주어진다. 알파벳 소문자와 '-', '='로만 이루어져 있다.

 

단어는 크로아티아 알파벳으로 이루어져 있다. 문제 설명의 표에 나와있는 알파벳은 변경된 형태로 입력된다.

 

출력

입력으로 주어진 단어가 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다.

 

입력되는 문자열에서 대응하는 크로아티아 문자열이 있는지 확인하여 글자 수를 구한다.

 

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    string input;
    cin >> input;
    int char_cnt = 0;
    string str_arr[8] = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
    for (int i = 0; i < input.length(); i++){
        bool matched = false;
        for (int j = 0; j < 8; j++){
            string croatian_char = str_arr[j];
            if (input.substr(i, croatian_char.length()) == croatian_char){
                char_cnt++;
                i += croatian_char.length() - 1;
                matched = true;
                break;
            }
        }
        if (!matched){
            char_cnt++;
        }
    }
    cout << char_cnt;
    return 0;
}

 

크로아티아 문자를 배열에 저장해 두고 입력된 문자열을 순회하면서 크로아티아 문자가 포함되어 있는지 검사한다.

 

검사할 때 크로아티아 문자 배열을 순회하면서 하나씩 입력된 문자열의 인덱스를 기준으로 동일한지 검사한다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        string[] str_arr = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
        string input = Console.ReadLine();
        int char_cnt = 0;
        for (int i = 0; i < input.Length; i++){
            bool char_matched = false;
            for (int j = 0; j < str_arr.Length; j++){
                string croatian_char = str_arr[j];
                if (i + croatian_char.Length <= input.Length &&
                    input.Substring(i, croatian_char.Length) == croatian_char){
                    char_cnt++;
                    i += croatian_char.Length - 1;
                    char_matched = true;
                    break;
                }
            }
            if (!char_matched) char_cnt++;
        }
        Console.WriteLine(char_cnt);
    }
}

 

 

Python

input_str = input()
str_arr = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="]
char_cnt = 0
i = 0
while i < len(input_str):
    is_char_matched = False
    for croatian_char in str_arr:
        if input_str[i:i+len(croatian_char)] == croatian_char:
            char_cnt += 1
            i += len(croatian_char)
            is_char_matched = True
            break
    if not is_char_matched:
        char_cnt += 1
        i += 1
print(char_cnt)

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim();
const croatian_chars = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="];
let char_cnt = 0;
for (let i = 0; i < input.length; i++){
    let is_char_matched = false;
    for (let j = 0; j < croatian_chars.length; j++){
        const croatian_char = croatian_chars[j];
        if (input.slice(i, i + croatian_char.length) === croatian_char){
            char_cnt += 1;
            i += croatian_char.length - 1;
            is_char_matched = true;
            break;
        }
    }
    if (!is_char_matched){
        char_cnt += 1;
    }
}
console.log(char_cnt);

 

7번 그룹 단어 체커

문제

그룹 단어란 단어에 존재하는 모든 문자에 대해서, 각 문자가 연속해서 나타나는 경우만을 말한다. 예를 들면, ccazzzzbb는 c, a, z, b가 모두 연속해서 나타나고, kin도 k, i, n이 연속해서 나타나기 때문에 그룹 단어이지만, aabbbccb는 b가 떨어져서 나타나기 때문에 그룹 단어가 아니다. 

 

단어 N개를 입력으로 받아 그룹 단어의 개수를 출력하는 프로그램을 작성하시오.

 

입력

첫째 줄에 단어의 개수 N이 들어온다. N은 100보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에 단어가 들어온다. 단어는 알파벳 소문자로만 되어있고 중복되지 않으며, 길이는 최대 100이다.

 

출력

첫째 줄에 그룹 단어의 개수를 출력한다.

 

N개의 입력을 받아서 해당 단어가 연속되는 문자인지 확인을 해야 한다. 연속은 동일한 문자 사이에 다른 문자가 등장했을 때 연속성이 깨진다.

 

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    int n;
    cin >> n;
    
    string word;
    int word_cnt = 0;
    while(cin >> word){
        bool is_seq_word = true;
        int char_arr[26] = {0};
        char last_char = '\0';
        for (char c : word){
            if (c != last_char){
                if (char_arr[c - 'a'] != 0){
                    is_seq_word = false;
                    break;
                }
                char_arr[c - 'a'] = 1;
            }
            last_char = c;
        }
        if (is_seq_word) 
            word_cnt++;
    }
    cout << word_cnt;
    return 0;
}

 

 

 

C#

using System;
class Program{
    static void Main(string[] args){
        int n = int.Parse(Console.ReadLine());
        int word_cnt = 0;
        for (int i = 0; i < n; i++){
            char last_char = '\0';
            int[] char_arr = new int[26];
            string word = Console.ReadLine();
            bool is_seq_word = true;
            foreach (char c in word){
                if (c != last_char){
                    if (char_arr[c - 'a'] != 0){
                        is_seq_word = false;
                        break;
                    }
                    char_arr[c - 'a'] = 1;
                }
                last_char = c;
            }
            if (is_seq_word)
                word_cnt++;
        }
        Console.WriteLine(word_cnt);
    }
}

 

Python

n = int(input())
word_cnt = 0;
for i in range(n):
    word = input();
    is_seq_word = True
    last_char = '\0'
    char_arr = [0] * 26
    for c in word:
        if c != last_char:
            if char_arr[ord(c) - ord('a')] != 0:
                is_seq_word = False
                break
            char_arr[ord(c) - ord('a')] = 1
        last_char = c
    if is_seq_word:
        word_cnt += 1
print(word_cnt)

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim().split('\n');
const n = parseInt(input[0]);
let word_cnt = 0;
for (let i = 1; i <= n; i++){
    const char_arr = Array(26).fill(0);
    const word = input[i];
    let is_seq_word = true;
    let last_char = '\0';
    for (const c of word){
        if (c !== last_char){
            if (char_arr[c.charCodeAt(0) - 'a'.charCodeAt(0)]){
                is_seq_word = false;
                break;
            }
            char_arr[c.charCodeAt(0) - 'a'.charCodeAt(0)] = 1;
        }
        last_char = c;
    }
    if (is_seq_word){
        word_cnt++;
    }
}
console.log(word_cnt);

 

8번 너의 평점은

문제

인하대학교 컴퓨터공학과를 졸업하기 위해서는, 전공평점이 3.3 이상이거나 졸업고사를 통과해야 한다. 그런데 아뿔싸, 치훈이는 깜빡하고 졸업고사를 응시하지 않았다는 사실을 깨달았다! 

 

치훈이의 전공평점을 계산해 주는 프로그램을 작성해 보자. 

 

전공평점은 전공과목별 (학점 × 과목평점)의 합을 학점의 총합으로 나눈 값이다. 

 

인하대학교 컴퓨터공학과의 등급에 따른 과목평점은 다음 표와 같다.

 

A+ 4.5
A0 4.0
B+ 3.5
B0 3.0
C+ 2.5
C0 2.0
D+ 1.5
D0 1.0
F 0.0

 

P/F 과목의 경우 등급이 P 또는 F로 표시되는데, 등급이 P인 과목은 계산에서 제외해야 한다. 

 

과연 치훈이는 무사히 졸업할 수 있을까?

 

입력

20줄에 걸쳐 치훈이가 수강한 전공과목의 과목명, 학점, 등급이 공백으로 구분되어 주어진다.

 

출력

치훈이의 전공평점을 출력한다. 

 

정답과의 절대오차 또는 상대오차가 \(10^{-4}\) 이하이면 정답으로 인정한다.

 

제한

- 1 ≤ 과목명의 길이 ≤ 50

- 과목명은 알파벳 대소문자 또는 숫자로만 이루어져 있으며, 띄어쓰기 없이 주어진다. 입력으로 주어지는 모든 과목명은 서로 다르다.

- 학점은 1.0,2.0,3.0,4.0중 하나이다.

- 등급은 A+, A0, B+, B0, C+, C0, D+, D0, F, P 중 하나이다.

- 적어도 한 과목은 등급이 P가 아님이 보장된다.

 

20과목 정보가 이름, 점수, 등급으로 각 줄에 입력된다.

 

P가 아닌 등급일 때만 점수를 계산한다.

 

C++

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
    float total_score = 0.0f;
    float sum_score = 0.0f;
    for (int i = 0; i < 20; i++){
        string name;
        float score;
        string grade;
        float grade_score;
        cin >> name >> score >> grade;
        if (grade == "A+"){
            grade_score = 4.5;
        }
        else if (grade == "A0"){
            grade_score = 4.0;
        }
        else if (grade == "B+"){
            grade_score = 3.5;
        }
        else if (grade == "B0"){
            grade_score = 3.0;
        }
        else if (grade == "C+"){
            grade_score = 2.5;
        }
        else if (grade == "C0"){
            grade_score = 2.0;
        }
        else if (grade == "D+"){
            grade_score = 1.5;
        }
        else if (grade == "D0"){
            grade_score = 1.0;
        }
        else if (grade == "F"){
            grade_score = 0.0;
        }
        
        if (grade != "P"){
            sum_score += score;
            total_score += score * grade_score;
        }
    }
    float result = total_score / sum_score;
    cout << fixed << setprecision(6) << result;
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        float sum_score = 0f;
        float total_score = 0f;
        for (int i = 0; i < 20; i++){
            string str = Console.ReadLine();
            string[] str_arr = str.Split();
            string name = str_arr[0];
            float score = float.Parse(str_arr[1]);
            string grade = str_arr[2];
            float grade_score = 0f;
            if (grade == "A+"){
                grade_score = 4.5f;
            }
            else if (grade == "A0"){
                grade_score = 4.0f;
            }
            else if (grade == "B+"){
                grade_score = 3.5f;
            }
            else if (grade == "B0"){
                grade_score = 3.0f;
            }
            else if (grade == "C+"){
                grade_score = 2.5f;
            }
            else if (grade == "C0"){
                grade_score = 2.0f;
            }
            else if (grade == "D+"){
                grade_score = 1.5f;
            }
            else if (grade == "D0"){
                grade_score = 1.0f;
            }
            else if (grade == "F"){
                grade_score = 0.0f;
            }
            if (grade != "P"){
                sum_score += score;
                total_score += score * grade_score;
            }
        }
        float result = total_score / sum_score;
        Console.WriteLine(result);
    }
}

 

Python

import sys
sum_score = 0;
total_score = 0;
for i in range(20):
    name, score, grade = sys.stdin.readline().strip().split()
    score = float(score)
    grade_score = 0;
    if grade != "P":
        if grade == "A+":
            grade_score = 4.5
        elif grade == "A0":
            grade_score = 4.0
        elif grade == "B+":
            grade_score = 3.5
        elif grade == "B0":
            grade_score = 3.0
        elif grade == "C+":
            grade_score = 2.5
        elif grade == "C0":
            grade_score = 2.0
        elif grade == "D+":
            grade_score = 1.5
        elif grade == "D0":
            grade_score = 1.0
        elif grade == "F":
            grade_score = 0.0
        sum_score += score
        total_score += score * grade_score
result = total_score / sum_score
print(f"{result:.6f}")

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim().split('\n');
let total_score = 0.0;
let sum_score = 0.0;
for (let i = 0; i < 20; i++){
    const str = input[i].split(' ');
    const name = str[0];
    const score = parseFloat(str[1]);
    const grade = str[2];
    let grade_score = 0.0;
    if (grade === "A+")
    {
        grade_score = 4.5;
    }
    else if (grade === "A0")
    {
        grade_score = 4.0;
    }
    else if (grade === "B+")
    {
        grade_score = 3.5;
    }
    else if (grade === "B0")
    {
        grade_score = 3.0;
    }
    else if (grade === "C+")
    {
        grade_score = 2.5;
    }
    else if (grade === "C0")
    {
        grade_score = 2.0;
    }
    else if (grade === "D+")
    {
        grade_score = 1.5;
    }
    else if (grade === "D0")
    {
        grade_score = 1.0;
    }
    else if (grade === "F")
    {
        grade_score = 0.0;
    }
    if (grade != "P"){
        sum_score += score;
        total_score += score * grade_score;
    }
}
const result = total_score / sum_score;
console.log(result.toFixed(6));
728x90
반응형

+ Recent posts