0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypeScriptで命令型と宣言型を書き比べてみる

Posted at

概要

せっかくJavaScriptがマルチパラダイムな言語なので書き比べてみます。
ずっと命令型なスタイルで開発していたので、宣言型なスタイルは慣れないんですよね。
実行するべき関数を組み立ててくみたいな考え方の切り替えに苦戦しています。

命令型

class Person
{
  private name: string;
  private age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  public sameAgePersons(persons: Person[]): Person[] {
    return persons.filter((person: Person) => this.age === person.age);
  }
}

const p1 = new Person('一郎', 20);
const p2 = new Person('二郎', 19);
const p3 = new Person('三郎', 20);

console.log(p1.sameAgePersons([p2, p3]));

宣言型

type Person = { name: string, age: number };

const p1: Person = {name: '一郎', age: 20};
const p2: Person = {name: '二郎', age: 19};
const p3: Person = {name: '三郎', age: 20};

const selectorSameAge = (age: number) => (person: Person) => age === person.age;
const findPersonsBySelector = (persons: Person[], selector: (person: Person) => boolean) => persons.filter(selector);
console.log(findPersonsBySelector([p2, p3], selectorSameAge(p1.age)));
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?