banner
biuaxia

biuaxia

"万物皆有裂痕,那是光进来的地方。"
github
bilibili
tg_channel

精通 TypeScript

標題:精通 TypeScript
日期:2022-02-17 16:02:14
toc:true
類別:

  • typescript
    標籤:
  • 精通
  • typescript

一等公民與高階函數#

一等公民:變數類型、值 (literal)、物件欄位、函數參數、函數返回都可以是函數。

高階函數:函數返回和函數參數都是高階函數,包裹一層算一階。

見程式碼:

let a = [1, 2, 3, 4, 11, 22, 33, 44, 111, 222, 333, 444]
a.sort()
console.log(a)

const comp = createCompare({
    smallerFirst: true
})

function createCompare(p: { smallerFirst: boolean }) {
    if (p.smallerFirst) {
        return (a: number, b: number) => a - b
    } else {
        return (a: number, b: number) => b - a
    }
}

function logCompare(comp: (a: number, b: number) => number) {
    return (a: number, b: number) => {
        console.log(`compareing ${a} ${b}`)
        return comp(a, b)
    }
}

a.sort(logCompare(comp))
console.log(a)

執行結果:

[LOG]: [1, 11, 111, 2, 22, 222, 3, 33, 333, 4, 44, 444] 
[LOG]: "compareing 11 1" 
[LOG]: "compareing 111 11" 
[LOG]: "compareing 2 111" 
[LOG]: "compareing 2 11" 
[LOG]: "compareing 2 1" 
[LOG]: "compareing 22 11" 
[LOG]: "compareing 22 111" 
[LOG]: "compareing 222 11" 
[LOG]: "compareing 222 111" 
[LOG]: "compareing 3 22" 
[LOG]: "compareing 3 2" 
[LOG]: "compareing 3 11" 
[LOG]: "compareing 33 11" 
[LOG]: "compareing 33 111" 
[LOG]: "compareing 33 22" 
[LOG]: "compareing 333 22" 
[LOG]: "compareing 333 111" 
[LOG]: "compareing 333 222" 
[LOG]: "compareing 4 22" 
[LOG]: "compareing 4 3" 
[LOG]: "compareing 4 11" 
[LOG]: "compareing 44 22" 
[LOG]: "compareing 44 222" 
[LOG]: "compareing 44 111" 
[LOG]: "compareing 44 33" 
[LOG]: "compareing 444 22" 
[LOG]: "compareing 444 111" 
[LOG]: "compareing 444 333" 
[LOG]: [1, 2, 3, 4, 11, 22, 33, 44, 111, 222, 333, 444]

其中變數、函數和方法的類型分別為:

let a: number[]

const comp: (a: number, b: number) => number

function createCompare(p: { smallerFirst: boolean }): (a: number, b: number) => number

function logCompare(comp: (a: number, b: number) => number): (a: number, b: number) => number

(method) Array<number>.sort(compareFn?: ((a: number, b: number) => number) | undefined): number[]

閉包#

見程式碼:

const a = [1, 2, 3, 4, 11, 22, 33, 44, 111, 222, 333, 444, 5, 55, 555, 6, 66, 666]

// config
const GOOD_FACTOR = 2
// config end

function isGoodNum(goodFactor: number, v: number) {
    return v % goodFactor == 0
}

function filterArray(a: number[], f: (v: number) => boolean) {
    return a.filter(f)
}

function partiallyApply(f: (a: number, b: number) => boolean, a: number) {
    return (b: number) => f(a, b)
}

console.log(filterArray(a, (v) => isGoodNum(GOOD_FACTOR, v)))
console.log(filterArray(a, partiallyApply(isGoodNum, 3)))

執行結果:

[LOG]: [2, 4, 22, 44, 222, 444, 6, 66, 666] 
[LOG]: [3, 33, 111, 222, 333, 444, 555, 6, 66, 666] 
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。