덕 타이핑
Coddy의 C++ 개발자를 위한 JavaScript 코스 레슨. 48개 중 40번째.
C++의 가상 기반 클래스와 템플릿은 서로 다른 검사 및 디스패치 모델로 상호 교환 가능한 동작을 표현할 수 있습니다. JavaScript의 덕 타이핑은 implements 선언 없이 런타임에 예상되는 호출 가능한 메서드만 있으면 됩니다. 대체 협력 객체를 직접 테스트하고, 올바른 철자의 속성이라면 호환되는 동작을 해야 한다고 가정하는 대신 계약을 문서화하세요.
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 Sender {virtual std::string send(std::string text)const=0;virtual ~Sender()=default;};struct Loud:Sender {std::string send(std::string text)const override{for(char& c:text)c=static_cast<char>(std::toupper(static_cast<unsigned char>(c)));return text;}};
int main() {
std::cout << std::boolalpha;
Loud sender;std::cout << sender.send("hi") << "\n";
}
JavaScript
class Loud { send(text) { return text.toUpperCase(); } }
console.log(new Loud().send("hi"));포팅 시 주의할 점: 필요한 메서드를 호출하세요. 채널 객체 자체가 반드시 호출 가능한 것은 아닙니다.
이 작업에서도 새로운 입력에 같은 규칙이 적용됩니다. 제공된 solve 함수에서 값을 반환하고, 입력 및 출력 처리는 driver.js에 그대로 두세요.
챌린지
쉬움입력은 ASCII 문자열입니다. Plain.send는 입력을 변경하지 않고 반환하고, Loud.send는 대문자로 반환합니다. 각 채널 하나씩에서 send를 호출한 결과를 반환하세요.
입력은 JSON 값 하나입니다. 잠금 해제된 파일을 수정하되, exercise.js부터 시작하세요. 잠긴 파일로 표시된 driver.js는 solve(input)을 호출하고 반환값을 공백 없는 JSON으로 출력한 다음 줄바꿈 하나를 출력합니다. 진단용 출력을 추가하지 마세요. 테스트는 전체 출력을 비교합니다. 모든 숫자 입력과 계산된 정수 합계는 안전한 정수 범위 내에 있습니다.
입력 예시:
"hi"예상 출력:
["hi","HI"]잠긴 드라이버는 solve를 호출하기 전에 새 인스턴스를 사용해 내보낸 클래스 API도 직접 확인합니다. 이름이 지정된 클래스와 문서화된 필드 및 메서드를 구현하세요. 최종 출력만 재현하는 것으로는 충분하지 않습니다. driver.js에서 모든 고정 검사를 확인할 수 있습니다.
직접 해보기
import assert from "node:assert/strict";
// 고정된 API 검증: 클래스 모듈은 과제 명세의 일부입니다.
import { Plain } from "./Plain.js";
import { Loud } from "./Loud.js";
const plain=new Plain(), loud=new Loud();
assert.equal(plain.send("MiX 2"),"MiX 2");
assert.equal(loud.send("MiX 2"),"MIX 2");
assert.equal(plain.send(""),""); assert.equal(loud.send(""),"");
assert.equal(loud.send("again"),"AGAIN");
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)));
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 JavaScript의 모든 레슨
직접 연습해 보세요: 온라인 JavaScript 컴파일러