1.判断数值符号是否相同
c
function numericSymbolsIsEqual(x: number, y: number): boolean {
return (x ^ y) >= 0
}
console.log(numericSymbolsIsEqual(1, 1))
console.log(numericSymbolsIsEqual(-1, 1))
console.log(numericSymbolsIsEqual(1, -1))
console.log(numericSymbolsIsEqual(-1, -1))
输出如下
判断一个数n是否为2的整数幂
代码部分
ts
function isPowerOfTwo(n: number): boolean {
return (n & (n - 1)) === 0
}
console.log(isPowerOfTwo(4))
console.log(isPowerOfTwo(5))
console.log(isPowerOfTwo(6))
console.log(isPowerOfTwo(1024))
console.log(isPowerOfTwo(1021))
输出如下
星级评分
ts
enum Score {
veryPoor = 1,
poor,
ordinary,
good,
veryGood
}
function starRating(n: Score): string {
return '★★★★★☆☆☆☆☆'.slice(5 - n, 10 - n)
}
console.log(starRating(Score.veryPoor))
console.log(starRating(Score.poor))
console.log(starRating(Score.ordinary))
console.log(starRating(Score.good))
console.log(starRating(Score.veryGood))
输出如下
0和1切换
typescript
function toggle(n: number): number {
return n ^= 1
}
console.log(toggle(1))
console.log(toggle(1))
console.log(toggle(0))
console.log(toggle(0))
console.log(toggle(1))
浮点数向下取整
typescript
function roundDownDoubleNon(n: number): number {
return ~~n
}
function roundDownRightShift(n: number): number {
return n >> 0
}
function roundDownLeftShift(n: number): number {
return n << 0
}
function roundDownOr(n: number): number {
return n | 0
}
console.log(roundDownDoubleNon(Math.PI))
console.log(roundDownRightShift(Math.PI))
console.log(roundDownLeftShift(Math.PI))
console.log(roundDownOr(Math.PI))
x乘2的y次幂
typescript
function getTwoYPower(x: number, y: number): number {
return x << y
}
// 输出1乘2的2次方
console.log(getTwoYPower(1, 2))
// 输出2乘2的3次方
console.log(getTwoYPower(2, 3))
// 输出3乘2的2次方
console.log(getTwoYPower(3, 2))
让天底下的代码再也没有bug
typescript
try {
//code
} catch (error) {
location.href = `https://baidu.com/esarch?q=js+${error.message}`
}
这个就不做演示啦哈