PHP's is_finite in TypeScript

Rosetta Stone: python/isfinite

How to use

Install via yarn add locutus and import: import { is_finite } from 'locutus/php/math/is_finite'.

Or with CommonJS: const { is_finite } = require('locutus/php/math/is_finite')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1is_finite(Infinity)false
2is_finite(-Infinity)false
3is_finite(0)true

Here's what our current TypeScript equivalent to PHP's is_finite looks like.

import type { PhpRuntimeValue } from '../_helpers/_phpTypes.ts'

type NumberCheckValue = PhpRuntimeValue

export function is_finite(val: NumberCheckValue): boolean {
// discuss at: https://locutus.io/php/is_finite/
// original by: Onno Marsman (https://twitter.com/onnomarsman)
// example 1: is_finite(Infinity)
// returns 1: false
// example 2: is_finite(-Infinity)
// returns 2: false
// example 3: is_finite(0)
// returns 3: true

let warningType = ''

if (val === Infinity || val === -Infinity) {
return false
}

// Some warnings for maximum PHP compatibility
if (typeof val === 'object') {
warningType = Array.isArray(val) ? 'array' : 'object'
} else if (typeof val === 'string' && !/^[+-]?\d/.test(val)) {
// simulate PHP's behaviour: '-9a' doesn't give a warning, but 'a9' does.
warningType = 'string'
}
if (warningType) {
const msg = 'Warning: is_finite() expects parameter 1 to be double, ' + warningType + ' given'
throw new Error(msg)
}

return true
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP math functions


Star