Menu
CoddyTech

컴포지션

Coddy의 C++ 개발자를 위한 JavaScript 코스 레슨. 48개 중 38번째.

C++의 컴포지션은 값을 저장할 수도 있고, 참조나 스마트 포인터를 저장할 수도 있으며, 각각 소유권 계약이 있습니다. JavaScript의 협력 객체는 객체 참조입니다. 하나를 저장해도 복제되지는 않습니다. 호출자가 제공한 동작을 주입하고, 기본 구현으로 대체하는 대신 문서화된 메서드에 위임하세요. 일반 JavaScript는 해당 메서드 계약을 정적으로 검증하지 않습니다.

C++

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <optional>
#include <functional>
#include <sstream>
#include <variant>
#include <memory>
#include <cctype>
#include <stdexcept>

struct Fee {int amount()const{return 4;}};struct Checkout {const Fee& fee;int total(int n)const{return n+fee.amount();}};
int main() {
std::cout << std::boolalpha;
Fee fee;Checkout checkout{fee};std::cout << checkout.total(6) << "\n";
}

JavaScript

class Fee { amount() { return 4; } }
class Checkout { constructor(fee) { this.fee=fee; } total(n) { return n+this.fee.amount(); } }
console.log(new Checkout(new Fee()).total(6));

포팅 시 주의할 점: 대입은 협력 객체의 깊은 복사본을 만드는 대신 해당 객체를 공유합니다.

이 과제에서도 새로운 입력에 같은 규칙을 적용합니다. 제공된 solve 함수에서 값을 반환하고, 입력 및 출력 처리는 driver.js에 그대로 두세요.

challenge icon

챌린지

쉬움

입력은 [subtotal,fee]입니다. Fee 객체를 만들고 Checkout에 주입하세요. checkout.total(subtotal)을 반환하세요. 두 값은 음이 아닌 정수입니다.

입력은 JSON 값 하나입니다. 잠금 해제된 파일을 수정하세요. exercise.js부터 시작하세요. 화면에 표시되는 잠긴 driver.js는 solve(input)을 호출하고 반환값을 압축된 JSON으로 출력한 뒤 줄바꿈 문자 하나를 출력합니다. 진단용 출력을 추가하지 마세요. 테스트는 전체 출력을 비교합니다. 모든 숫자 입력과 계산된 정수 합계는 안전한 정수 범위 내에 있습니다.

입력 예시:

[6,4]

예상 출력:

10

잠긴 드라이버는 solve를 호출하기 전에 새 인스턴스를 사용해 내보낸 클래스 API도 직접 확인합니다. 이름이 지정된 클래스와 문서화된 필드 및 메서드를 구현하세요. 최종 출력만 재현하는 것으로는 충분하지 않습니다. driver.js에서 모든 고정 검사를 확인할 수 있습니다.

Checkout은 주입된 객체를 보유하고 각 total 계산 때마다 그 객체의 amount() 메서드를 호출해야 합니다. 여기에는 해당 메서드를 구현하는 다른 객체도 포함됩니다.

직접 해보기

import assert from "node:assert/strict";
// 고정된 API 검사: 클래스 모듈은 과제의 계약에 포함됩니다.
import { Fee } from "./Fee.js";
import { Checkout } from "./Checkout.js";
const fee=new Fee(4), checkout=new Checkout(fee);
assert.equal(fee.amount(),4); assert.equal(checkout.total(6),10);
assert.equal(new Checkout(new Fee(0)).total(5),5);
const changing={amount() { return 7; }};
const other=new Checkout(changing);
assert.equal(other.total(2),9);
changing.amount=()=>1;
assert.equal(other.total(2),3);
import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin으로 JSON 값 하나가 들어옵니다. 데이터를 반환하세요. solve 내부에서 출력하지 마세요.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 JavaScript의 모든 레슨

직접 연습해 보세요: 온라인 JavaScript 컴파일러