Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

Typescript - 2) more on design patterns with TS 본문

TypeScript

Typescript - 2) more on design patterns with TS

보람- 2024. 1. 11. 17:30

 

- 초기 세팅하기

tsc --init
npm init -y
npm i nodemon concurrently

 

 

- nodemon 설치 후 scripts 수정하기

{
  "name": "sort",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start:build": "tsc -w",
    "start:run": "nodemon build/index.js",
    "start": "concurrently npm:start:*"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "concurrently": "^8.2.2",
    "nodemon": "^3.0.2"
  }
}

 

 

 

** sort (bubble)

class Sorter {
  // collection:number[]

  constructor(public collection: number[]) {
    // this.collection= collection
  }

  sort(): void {
    const { length } = this.collection;

    for (let i = 0; i < length; i++) {
      for (let j = 0; j < length - i - 1; j++) {
        if (this.collection[j] > this.collection[j + 1]) {
          const lefthand = this.collection[j];
          this.collection[j] = this.collection[j + 1];
          this.collection[j + 1] = lefthand;
        }
      }
    }
  }
}

const sorter = new Sorter([10, 3, -5, 0]);
sorter.sort();
console.log(sorter.collection);

 

- bubble sort는 두개를 쌍으로 두고 왼쪽과 오른쪽을 비교해, 큰 수가 오른쪽에 위치하게 자리를 바꿔

- 가장 큰 수가 가장 오른쪽에 하는 정렬방법으로

- 두개를 비교해서, 자리를 바꾸는걸 생각해서 interface를 사용하여 어떤 type이여도 코드를 재사용할수있게 만들기

// sorter.ts

interface Sortable {
  length: number;
  compare(leftIndex: number, rightIndex: number): boolean;
  swap(leftIndex: number, rightIndex: number): void;
}

export class Sorter {
  constructor(public collection: Sortable) {}

  sort(): void {
    const { length } = this.collection;

    for (let i = 0; i < length; i++) {
      for (let j = 0; j < length - i - 1; j++) {
        if (this.collection.compare(j, j + 1)) {
          this.collection.swap(j, j + 1);
        }
      }
    }
  }
}

 

 

 

 

** number sort

export class NumbersCollection {
  constructor(public data: number[]) {}

  get length(): number {
    return this.data.length;
  }

  compare(leftIndex: number, rightIndex: number): boolean {
    return this.data[leftIndex] > this.data[rightIndex];
  }

  swap(leftIndex: number, rightIndex: number): void {
    const lefthand = this.data[leftIndex];
    this.data[leftIndex] = this.data[rightIndex];
    this.data[rightIndex] = lefthand;
  }
}

// const collection = new NumbersCollection([1, 2, 3]);
// collection.length;
// length() 앞에 get을 붙인이유
import { Sorter } from './Sorter';
import { NumbersCollection } from './NumbersCollection';

const numberCollection = new NumbersCollection([100, 3, -5, 0]);
const sorter = new Sorter(numberCollection);
sorter.sort();
console.log(numberCollection.data);

// [ -5, 0, 3, 100 ]

 

 

 

** string sort

export class ChaCollection {
  constructor(public data: string) {}

  get length(): number {
    return this.data.length;
  }

  compare(leftIndex: number, rightIndex: number): boolean {
    return (
      this.data[leftIndex].toLowerCase() > this.data[rightIndex].toLowerCase()
    );
  }

  swap(leftIndex: number, rightIndex: number): void {
    const characters = this.data.split('');

    const lefthand = characters[leftIndex];
    characters[leftIndex] = characters[rightIndex];
    characters[rightIndex] = lefthand;

    this.data = characters.join('');
  }
}
import { Sorter } from './Sorter';
import { ChaCollection } from './CharCollection';

const charactersCollection = new ChaCollection('Xaayb');
const sorter = new Sorter(charactersCollection);
sorter.sort();
console.log(charactersCollection.data);
// aabXy

 

 

 

 

** LinkedList 

- linkedList class를 만들어 추가하고, 길이를 구하고, 비교하고, 바꾸고, 출력할 메서드를 생성

   - class로 만들었기때문에 인스턴스 생성해서 작성해야하는 번거로움이 생김

 

- 아예 정렬을 해주는 클래스를 추상클래스로 만들어 사용하기

   - length, compare, swap

   - 추상클래스는 인스턴스를 만들수없다!

 


※ typeof, instanceof

 

 

'TypeScript' 카테고리의 다른 글

Typescript - design patterns with TS ①  (0) 2024.01.11
TypeScript - 전략패턴(Strategy Pattern)  (0) 2024.01.05
TypeScript - 제네릭(generics), tuple, interface  (0) 2024.01.05
TypeScript  (0) 2024.01.04