首页 > 编程语言 >[Javascript] Object.freeze: using Object.freeze in function params to enforce immutabtility

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

时间:2022-08-15 19:24:44浏览次数:61  
标签:function luckLotteryNumbers Object number freeze numbers

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())

标签:function,luckLotteryNumbers,Object,number,freeze,numbers
From: https://www.cnblogs.com/Answer1215/p/16589378.html

相关文章