Open6

TypeScript CodeSnippets

4時4時

配列内の各オブジェクトにプロパティを追加する

const items = [{name: 'apples'}, {name: 'bananas'}, {name: 'cherries'}]
const inventory: inventory[] = items.reduce((acc, item) => {
    const res = [
        ...acc,
        {
            name: item.name,
            quantity: getQuantity(item.name),
        } as inventory
    ]
    return res
}, [] as inventory[])
console.log(inventory) // [{"name": "apples", "quantity": 100}, {...}] 

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

4時4時

オブジェクトの配列から重複する要素を削除し配列に変換する

const items = [{name: 'apples'}, {name: 'bananas'}, {name: 'apples'}]
const res = items.map((v) => v.name).filter((val, index, self) => self.indexOf(val) === index)
console.log(res) // ["apples", "bananas"] 
const items = [{name: 'apples'}, {name: 'bananas'}, {name: 'apples'}]
const res = [...new Set(items.map((v) => v.name))]
console.log(res) // ["apples", "bananas"] 

https://qiita.com/netebakari/items/7c1db0b0cea14a3d4419

4時4時

条件によって値を返す処理色々

if

let quantity = 0
if (item === items.apples) {
  quantity = 10
} else if (item === items.bananas) {
  quantity = 8
}

switch-case

let quantity = 0
switch (item) {
  case items.apples:
    quantity = 10
    break
}

switch-case(即時関数)

const quantity = ((item: ItemType): number => {
  switch (item) {
    case items.apples:
      return 10
  }
})(items.apple)

dynamic dispatch

type GetQuantityActions = {
  [key in itemType]: () => number
}

const getQuantityActions: GetQuantityActions = {
  apples: () => 10,
  bananas: () => 8,
  cherries: () => 6,
}

const quantity = getQuantityActions[item] ? getQuantityActions[item]() : 0