[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 luckLotteryNumber
should not be changed, and telling the co-workers, it is immutable, enforce immtuable code
luckLotteryNumbers = recordNumber(Object.freeze(luckLotteryNumbers), lotteryNum())