둘째주 #10 Typescript 기초 -4

김선은·2023년 5월 24일

TS로 함수 만드는 연습!

TS Playground

~.~ 수정해야함 ~.~
다시 치면서 익숙해져보자고

//콜 시그니처? -> 데이터 타입과 반환값의 타입 지정!
// 1. l!ast(arr) : 배열의 마지막 요소를 반환
interface Arr {
    <T>(arr: T[]): T
}

const last:Arr = (arr) => {
    const arrlength = arr.length
    return arr[arrlength - 1];
}

- - - - - - - - - - - - - - - - -
type Arr2 = <T>(items: T[) => T
const last2: Arr2 = (items) => items[items.length -1]

// 2. p!repend(arr, item) : 배열의 시작 부분에 item을 넣고 return
interface Prepend {
    <T>(arr: T[], item: T): T[]
}

const prepend:Prepend = (arr, item) => [item, ...arr]

- - - - - - - - - - - - - - - - -

// 3. m!ix(arr,arr) : 두개의 배열을 매개변수로 받아, 매개변수로 받은 두 배열을 하나의 배열로 섞어서 하나의 배열로 반환
function mix<T> (item: T[], item2: T[]) {
    return [...item, ...item2]
}

- - - - - - - - - - - - - - - - -

// 4. c!ount(arr) : 배열을 매개변수로 받아, 매개변수로 받아온 배열의 길이를 반환
interface Count {
    <T>(arr: T[]): T
}
const count:Count = (arr: any) => arr.length
    //console.log(count2(["a","b",1]))

function count2<T> (arr:T[]) {
    return arr.length
}
    //console.log(count([1,2,"zz"]))

- - - - - - - - - - - - - - - - -


// 5. f!indIndex(arr, item) : 첫번째 매개변수로 배열을, 두번째 매개변수로 받아온 item이 첫번째 매개변수 arr배열의 몇번째 index로
// 존재하는지 체크한후 존재한다면 몇번째 index인지 반환하고 존재하지않는다면 null을 반환
interface IFind {
    <T>(arr:T[], item:T): T
}
const findIndex:IFind = (arr:any, item) => {
    let answer = arr.indexOf(item)
    if (answer) return answer
    else if (answer === 0) return 0
    return null
}

- - - - - - - - - - - - - - - - -
// 6. s!lice(arr, startIndex, endIndex): 첫번째 매개변수로 배열 arr을 받고, 두번째 매개변수로 숫자 startIndex,
//세번째 매개변수 숫자 endIndex를 받습니다. 첫번째 매개변수 arr을 두번째 매개변수로 받은 startIndex부터 세번째 매개변수로 받은
//인덱스까지 자른 결과를 반환. 이때 세번째 매개변수는 필수 매개변수가 아닙니다.

type Slice = {
    <T>(arr:T[], startIndex:number, endIndex?:number) : T
}

    //let a = ["빨강", "주황", "노랑", "초록", "파랑"] a.slice(2,4) 는 ["노랑", "초록"]

const slice:Slice = (arr:any ,start,end?) => arr.slice(start,end)

    //console.log(slice([13,14,15,16],2))
type Words = {
    [key: string]: string
}

class Dict {
    private words: Words; // 문자로된 키, 값 모양임을 알려줌
    constructor() {
        this.words = {} // term: def 들어옴
    }
    add(word: Word){ // 클래스를 타입처럼 썼다
        if(this.words[word.term] === undefined) {
            this.words[word.term] = word.def
        }
    }
    get(term: string){
        return this.words[term]
    }
    delete(word: Word){
        if(this.words[word.term]) delete this.words[word.term]
    }
    update(word:Word){ //왜안되지
        if(this.words[word.term]) {
            this.words[word.term] = word.def
        }
    }
    showAll () {
        return Object.keys(this.words).forEach(term => console.log(term))
    } // 객체 키 값 얻기
    count() {
        return Object.keys(this.words).length
    }
    upsert(word:Word) {
        this.words[word.term] = word.def
    }
    exists(term:string) {
        if(this.words[term]) { //words.term 하면 안됨
            return true
        } return false
    }
    // bulkAdd(wordArr:Word[]) {
    //     if(this.words[Word.term] === undefined) {
    //         wordArr.map((w) => this.add(new Word(w[0], w[1])))
    //     }
    // }
    bulkAdd(bulk: Word[]) {
        bulk.forEach((word: Word) => {
            if (this.words[word.term] === undefined)
            this.words[word.term] = word.def
        })
    }
    bulkDelete(bulk: string[]) {
        bulk.forEach((word: string) => {
            if(this.words[word]) 
            delete this.words[word]
        })
    }
}
// constructor 내부에 쓰는거랑(property가 constructor로부터 바로 초기화되는것)
//외부에 ininializer 없이 선언하고 constructor에서 수동으로 초기화하는 차이가 뭘까

class Word {
    constructor(
        public term: string,
        public def: string
    ) {}
}
// Word 클래스를 만들고 new 연산자로 새로운 Word 만듬.
const kimchi = new Word("kimchi", "한국 음식")
const pizza = new Word("pizza", "이태리 음식")
const hamberger = new Word("hamberger", "미국 음식")
const sushi = new Word("sushi", "일본 음식")
const bluefinTunaSushi = new Word("bluefinTunaSushi", "최강 초밥")
// 단어와 뜻을 가진 변수를 Word 클래스를 이용해서 만들었음

// 단어 추가하기
const dict = new Dict()
dict.add(kimchi)
dict.add(pizza)
dict.add(hamberger)
dict.add(sushi)
dict.add(bluefinTunaSushi)
//Word 클래스로 만든것을 Dict class를 이용해서 dict 만든곳에 add 하기!

console.log("1. 단어 정의 리턴하기")
console.log(dict.get("kimchi")) // 한국 음식

console.log("2. 단어 지우기")
dict.delete(sushi)

console.log("3. 단어 업데이트") // 어케하누
const egg = new Word("egg","필수품")
dict.update(egg)
console.log(dict.get("egg"))


console.log("4. 용어 보여주기")
dict.showAll()

console.log("5. 단어 갯수 세기")
console.log(dict.count())

console.log("6. upsert")
dict.upsert(new Word("kimchi", "김치 없인 못살아"))
console.log(dict.get("kimchi"))

console.log("7. exists")
console.log(dict.exists("kimchi"))
//console.log(dict)

console.log("8. bulkAdd")
dict.bulkAdd([{term:"닭가슴살", def:"득근득근"}, {term:"시리얼", def:"아침 대용"}])
dict.showAll()

console.log("9. bulkDelete")
dict.bulkDelete(["pizza", "hamberger"])
dict.showAll()

URL 단축 사이트
https://huchu.link/

profile
기록은 기억이 된다

0개의 댓글