今回はクラスを作る問題に挑戦!
社員番号と名前をまとめて、情報をサクッと取り出せるクラスを作ってみよう!
問題概要
-
Employeeクラスは 社員番号numberと名前nameのメンバ変数を持つ設計図 -
メンバ関数
getnum()とgetname()で情報を返す -
入力で「
make number name」があったら新社員を作成 -
「
getnum n」ならn番目の社員の番号、「getname n」なら名前を出力
入力例:
7
make 2742 mako
getnum 1
make 2782 taisei
getname 2
make 31 megumi
getname 1
getname 3
出力例:
2742
taisei
mako
megumi
✅ OK例:
const rl = require('readline').createInterface({input:process.stdin});
const lines = [];
rl.on ('line', (input) => {
lines.push(input);
});
rl.on ('close', () => {
const N = Number(lines[0]);
class Employee{
constructor(number, name){
this.number = Number(number);
this.name = name;
}
getnum() {
return this.number;
}
getname() {
return this.name;
}
}
const employees = [];
for (let i = 1; i <= N; i++) {
const tokens = lines[i].split(' ');
const command = tokens[0];
if (command === 'make') {
employees.push(new Employee(tokens[1], tokens[2]));
}
else if (command === 'getnum'){
const index = tokens[1] - 1;
console.log(employees[index].getnum());
}
else if (command === 'getname'){
const index = tokens[1] - 1;
console.log(employees[index].getname());
}
}
});
-
Employeeクラスはnumberとnameの2つのメンバ変数を持つ。
→クラス名を慣習通り大文字スタートのEmployee に - メンバ関数
getnum()とgetname()でそれぞれ番号と名前を返す。 -
makeは新しい社員を作って配列employeesに追加。 -
getnumとgetnameは指定された番号(1始まり)に対応する社員の情報を出力。
✅ OK例:バージョン2
const rl = require('readline').createInterface({ input: process.stdin });
const lines = [];
rl.on('line', (input) => {
lines.push(input);
});
rl.on('close', () => {
const N = Number(lines[0]);
class Employee {
constructor(number, name) {
this.number = Number(number);
this.name = name;
}
getnum() {
return this.number;
}
getname() {
return this.name;
}
}
const employees = [];
const output = [];
for (let i = 1; i <= N; i++) {
const tokens = lines[i].split(' ');
const command = tokens[0];
if (command === 'make') {
employees.push(new Employee(tokens[1], tokens[2]));
}
else if (command === 'getnum' || command === 'getname') {
const index = Number(tokens[1]) - 1;
if (index = employees.length) {
// 範囲外の場合はスキップ(問題文の範囲外は想定しなくて良いですが念のため)
continue;
}
if (command === 'getnum') {
output.push(employees[index].getnum());
}
else if (command === 'getname'){
output.push(employees[index].getname());
}
}
}
console.log(output.join('\n'));
});
- 出力を一括にまとめて、少しパフォーマンスの向上を意識
- 範囲外アクセスを防ぐ簡単なチェックを入れた
- (必要はないけど、念のため。保守性を意識してみた)
- コマンド判定を作成と出力で分けてみたけど微妙…?
🗒️メモ&まとめ
🔍クラス
- オブジェクトの設計図・テンプレート
- 似た性質を持つデータと処理をまとめる
- JavaScriptでは
classキーワードで定義
🔍メンバ変数(プロパティ)
- クラスの内部で保持するデータ
- インスタンスごとに値が異なることが多い
-
this.変数名でアクセス・定義する
🔍メンバ関数(メソッド)
- クラス内に定義された関数(処理)
- メンバ変数の値を扱ったり返したりする
-
thisを使ってインスタンスの状態にアクセス可能