[Javascript] Object.freeze: using Object.freeze in function params to enforce immutabtility

function lotteryNum() {
  return (Math.round(Math.random() * 100) % 58) + 1;
}

function recordNumber(luckLotteryNumbers: readonly number[], num: number): number[] {
  let numbers: number[] = luckLotteryNumbers.slice();
  if (!luckLotteryNumbers.includes(num)) {
    numbers = [
      ...numbers,
      num
    ].sort((x, y) => x - y)
  }
  return numbers;
}

let luckLotteryNumbers: number[] = [];

while(luckLotteryNumbers.length < 6) {
  luckLotteryNumbers = recordNumber(Object.freeze(luckLotteryNumbers), lotteryNum())
}

console.log(luckLotteryNumbers)

For following code, it enforce the luckLotteryNumbershould not be changed, and telling the co-workers, it is immutable, enforce immtuable code

luckLotteryNumbers = recordNumber(Object.freeze(luckLotteryNumbers), lotteryNum())
posted @ 2022-08-15 19:13  Zhentiw  阅读(17)  评论(0编辑  收藏  举报