isInt
檢查值是否為整數類型。
基礎用法
typescript
import { isInt } from 'radash'
console.log(isInt(42)) // true
console.log(isInt(3.14)) // false
console.log(isInt('42')) // false
console.log(isInt(NaN)) // false
console.log(isInt(Infinity)) // false
語法
typescript
function isInt(value: any): value is number
參數
value
(any): 要檢查的值
返回值
返回一個布爾值,如果值是整數則返回 true
,否則返回 false
。同時作為TypeScript類型守衛。
示例
基本類型檢查
typescript
import { isInt } from 'radash'
// 整數
console.log(isInt(42)) // true
console.log(isInt(0)) // true
console.log(isInt(-10)) // true
console.log(isInt(1000000)) // true
// 浮點數
console.log(isInt(3.14)) // false
console.log(isInt(-2.5)) // false
console.log(isInt(1.0)) // false
console.log(isInt(0.0)) // false
// 字符串
console.log(isInt('42')) // false
console.log(isInt('3.14')) // false
console.log(isInt('')) // false
// 其他類型
console.log(isInt(null)) // false
console.log(isInt(undefined)) // false
console.log(isInt(true)) // false
console.log(isInt(false)) // false
console.log(isInt([])) // false
console.log(isInt({})) // false
特殊數值檢查
typescript
import { isInt } from 'radash'
// NaN
console.log(isInt(NaN)) // false
// 無窮大
console.log(isInt(Infinity)) // false
console.log(isInt(-Infinity)) // false
// 最大/最小值
console.log(isInt(Number.MAX_VALUE)) // false
console.log(isInt(Number.MIN_VALUE)) // false
console.log(isInt(Number.MAX_SAFE_INTEGER)) // true
console.log(isInt(Number.MIN_SAFE_INTEGER)) // true
// 邊界值
console.log(isInt(Number.MAX_SAFE_INTEGER + 1)) // false
console.log(isInt(Number.MIN_SAFE_INTEGER - 1)) // false
類型守衛使用
typescript
import { isInt } from 'radash'
function processNumber(value: unknown) {
if (isInt(value)) {
// TypeScript 知道 value 是整數
console.log(`Processing integer: ${value}`)
return value * 2
}
if (typeof value === 'number') {
// 處理浮點數
console.log(`Processing float: ${value}`)
return Math.round(value * 2)
}
console.log('Not a number')
return null
}
console.log(processNumber(42)) // Processing integer: 42 84
console.log(processNumber(3.14)) // Processing float: 3.14 6
console.log(processNumber('abc')) // Not a number null
數組過濾
typescript
import { isInt } from 'radash'
const mixedArray = [1, 2.5, 3, 4.7, '5', 6.0, 7, 8.9, null, undefined]
const integers = mixedArray.filter(isInt)
console.log(integers) // [1, 3, 7]
const nonIntegers = mixedArray.filter(item => !isInt(item))
console.log(nonIntegers) // [2.5, 4.7, '5', 6.0, 8.9, null, undefined]
對象屬性檢查
typescript
import { isInt } from 'radash'
const data = {
id: 1,
price: 19.99,
quantity: 5,
rating: 4.5,
score: 100,
weight: 2.5,
isAvailable: true
}
const integerProperties = Object.entries(data)
.filter(([key, value]) => isInt(value))
.map(([key, value]) => ({ key, value }))
console.log(integerProperties)
// [
// { key: 'id', value: 1 },
// { key: 'quantity', value: 5 },
// { key: 'score', value: 100 }
// ]
表單驗證
typescript
import { isInt } from 'radash'
interface FormData {
age: unknown
quantity: unknown
price: unknown
score: unknown
}
function validateForm(data: FormData) {
const errors: string[] = []
if (!isInt(data.age)) {
errors.push('Age must be a whole number')
}
if (!isInt(data.quantity)) {
errors.push('Quantity must be a whole number')
}
if (typeof data.price !== 'number') {
errors.push('Price must be a number')
}
if (!isInt(data.score)) {
errors.push('Score must be a whole number')
}
return errors
}
console.log(validateForm({
age: 25,
quantity: 5,
price: 19.99,
score: 85
})) // []
console.log(validateForm({
age: 25.5,
quantity: '5',
price: 19.99,
score: 85.5
})) // ['Age must be a whole number', 'Quantity must be a whole number', 'Score must be a whole number']
API響應處理
typescript
import { isInt } from 'radash'
interface ApiResponse {
id: number
count: unknown
price: unknown
rating: unknown
}
function processApiResponse(response: ApiResponse) {
const processed = {
id: response.id,
count: isInt(response.count) ? response.count : 0,
price: typeof response.price === 'number' ? response.price : 0,
rating: typeof response.rating === 'number' ? response.rating : 0
}
return processed
}
const response1: ApiResponse = {
id: 1,
count: 5,
price: 19.99,
rating: 4.5
}
const response2: ApiResponse = {
id: 2,
count: '5',
price: '19.99',
rating: null
}
console.log(processApiResponse(response1))
// { id: 1, count: 5, price: 19.99, rating: 4.5 }
console.log(processApiResponse(response2))
// { id: 2, count: 0, price: 0, rating: 0 }
數學計算
typescript
import { isInt } from 'radash'
function calculateFactorial(value: unknown): number {
if (!isInt(value) || value < 0) {
return 0
}
let result = 1
for (let i = 2; i <= value; i++) {
result *= i
}
return result
}
function calculateDivisors(value: unknown): number[] {
if (!isInt(value) || value <= 0) {
return []
}
const divisors: number[] = []
for (let i = 1; i <= value; i++) {
if (value % i === 0) {
divisors.push(i)
}
}
return divisors
}
console.log(calculateFactorial(5)) // 120
console.log(calculateFactorial(3.14)) // 0
console.log(calculateDivisors(12)) // [1, 2, 3, 4, 6, 12]
console.log(calculateDivisors(3.5)) // []
數據庫查詢結果處理
typescript
import { isInt } from 'radash'
interface DatabaseRecord {
id: number
quantity: unknown
price: unknown
discount: unknown
}
function sanitizeDatabaseRecord(record: DatabaseRecord) {
return {
id: record.id,
quantity: isInt(record.quantity) ? record.quantity : 0,
price: typeof record.price === 'number' ? record.price : 0,
discount: typeof record.discount === 'number' ? record.discount : 0
}
}
const dbRecord: DatabaseRecord = {
id: 1,
quantity: 10,
price: 29.99,
discount: 5
}
console.log(sanitizeDatabaseRecord(dbRecord))
// { id: 1, quantity: 10, price: 29.99, discount: 5 }
配置文件處理
typescript
import { isInt } from 'radash'
interface Config {
port: unknown
maxConnections: unknown
timeout: unknown
retries: unknown
}
function validateConfig(config: Config) {
const errors: string[] = []
if (!isInt(config.port)) {
errors.push('port must be a whole number')
}
if (!isInt(config.maxConnections)) {
errors.push('maxConnections must be a whole number')
}
if (typeof config.timeout !== 'number') {
errors.push('timeout must be a number')
}
if (!isInt(config.retries)) {
errors.push('retries must be a whole number')
}
return errors
}
const validConfig: Config = {
port: 3000,
maxConnections: 10,
timeout: 5000.5,
retries: 3
}
const invalidConfig: Config = {
port: '3000',
maxConnections: 10.5,
timeout: '5000ms',
retries: 3.2
}
console.log(validateConfig(validConfig)) // []
console.log(validateConfig(invalidConfig)) // ['port must be a whole number', 'maxConnections must be a whole number', 'timeout must be a number', 'retries must be a whole number']
游戲開發
typescript
import { isInt } from 'radash'
interface PlayerStats {
level: unknown
health: unknown
mana: unknown
experience: unknown
}
function validatePlayerStats(stats: PlayerStats) {
const validStats: Partial<PlayerStats> = {}
if (isInt(stats.level)) {
validStats.level = stats.level
}
if (isInt(stats.health)) {
validStats.health = stats.health
}
if (isInt(stats.mana)) {
validStats.mana = stats.mana
}
if (isInt(stats.experience)) {
validStats.experience = stats.experience
}
return validStats
}
const playerStats: PlayerStats = {
level: 10,
health: 100,
mana: 50,
experience: 1250
}
console.log(validatePlayerStats(playerStats))
// { level: 10, health: 100, mana: 50, experience: 1250 }
金融計算
typescript
import { isInt } from 'radash'
interface FinancialData {
principal: unknown
years: unknown
rate: unknown
payments: unknown
}
function calculateSimpleInterest(data: FinancialData): number {
if (!isInt(data.years) || !isInt(data.payments)) {
return 0
}
if (typeof data.principal !== 'number' || typeof data.rate !== 'number') {
return 0
}
return data.principal * data.rate * data.years
}
function validateFinancialData(data: FinancialData) {
const errors: string[] = []
if (typeof data.principal !== 'number') {
errors.push('Principal must be a number')
}
if (!isInt(data.years)) {
errors.push('Years must be a whole number')
}
if (typeof data.rate !== 'number') {
errors.push('Rate must be a number')
}
if (!isInt(data.payments)) {
errors.push('Payments must be a whole number')
}
return errors
}
const loanData: FinancialData = {
principal: 10000,
years: 5,
rate: 0.05,
payments: 12
}
console.log(calculateSimpleInterest(loanData)) // 2500
console.log(validateFinancialData(loanData)) // []
科學計算
typescript
import { isInt } from 'radash'
function isPrime(value: unknown): boolean {
if (!isInt(value) || value < 2) {
return false
}
for (let i = 2; i <= Math.sqrt(value); i++) {
if (value % i === 0) {
return false
}
}
return true
}
function getPrimeFactors(value: unknown): number[] {
if (!isInt(value) || value < 2) {
return []
}
const factors: number[] = []
let n = value
for (let i = 2; i <= Math.sqrt(n); i++) {
while (n % i === 0) {
factors.push(i)
n /= i
}
}
if (n > 1) {
factors.push(n)
}
return factors
}
console.log(isPrime(17)) // true
console.log(isPrime(15)) // false
console.log(isPrime(3.14)) // false
console.log(getPrimeFactors(12)) // [2, 2, 3]
console.log(getPrimeFactors(3.5)) // []
數組處理
typescript
import { isInt } from 'radash'
function findIntegers(array: unknown[]): number[] {
return array.filter(isInt)
}
function calculateIntegerStats(array: unknown[]) {
const integers = findIntegers(array)
if (integers.length === 0) {
return { count: 0, sum: 0, average: 0, min: null, max: null }
}
return {
count: integers.length,
sum: integers.reduce((sum, val) => sum + val, 0),
average: integers.reduce((sum, val) => sum + val, 0) / integers.length,
min: Math.min(...integers),
max: Math.max(...integers)
}
}
const mixedArray = [1, 2.5, 3, 4.7, '5', 6, 7.8, 8, 9.1, 10]
console.log(findIntegers(mixedArray)) // [1, 3, 6, 8, 10]
console.log(calculateIntegerStats(mixedArray))
// { count: 5, sum: 28, average: 5.6, min: 1, max: 10 }
邊界值測試
typescript
import { isInt } from 'radash'
// 測試邊界值
const boundaryTests = [
Number.MAX_SAFE_INTEGER,
Number.MIN_SAFE_INTEGER,
Number.MAX_SAFE_INTEGER + 1,
Number.MIN_SAFE_INTEGER - 1,
0,
-0,
1,
-1,
1.0,
-1.0,
1.1,
-1.1
]
boundaryTests.forEach(value => {
console.log(`${value} is integer: ${isInt(value)}`)
})
// 9007199254740991 is integer: true
// -9007199254740991 is integer: true
// 9007199254740992 is integer: false
// -9007199254740992 is integer: false
// 0 is integer: true
// 0 is integer: true
// 1 is integer: true
// -1 is integer: true
// 1 is integer: true
// -1 is integer: true
// 1.1 is integer: false
// -1.1 is integer: false
性能測試
typescript
import { isInt } from 'radash'
function benchmarkIsInt() {
const testValues = [
1, 2, 3, 4, 5,
1.1, 2.2, 3.3, 4.4, 5.5,
'1', '2', '3', '4', '5',
null, undefined, true, false,
[], {}, () => {}
]
const iterations = 1000000
const start = performance.now()
for (let i = 0; i < iterations; i++) {
testValues.forEach(value => {
isInt(value)
})
}
const end = performance.now()
console.log(`Benchmark completed in ${end - start}ms`)
}
// benchmarkIsInt() // 運行性能測試
注意事項
- 整數定義: 只檢查真正的整數,不包括浮點數
- 安全整數: 超出安全整數范圍的值返回false
- 類型守衛: 作為TypeScript類型守衛使用
- 性能: 檢查速度很快,適合高頻使用
- 邊界值: 正確處理0、負數、最大/最小安全整數
與其他方法的區別
isInt()
: 檢查是否為整數Number.isInteger()
: 原生JavaScript方法isNumber()
: 檢查是否為數字(包括浮點數)Number.isSafeInteger()
: 檢查是否為安全整數
實際應用場景
- 表單驗證: 驗證用戶輸入的整數
- API處理: 處理API響應中的整數字段
- 數據庫操作: 驗證數據庫字段類型
- 數學計算: 確保計算參數為整數
- 游戲開發: 處理游戲中的整數值
- 金融應用: 處理貨幣和數量計算