PHP's is_infinite in TypeScript

Rosetta Stone: python/isinf

How to use

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

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

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_infinite(Infinity)true
2is_infinite(-Infinity)true
3is_infinite(0)false

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

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

type NumberCheckValue = PhpRuntimeValue

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

let warningType = ''

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

// 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_infinite() expects parameter 1 to be double, ' + warningType + ' given'
throw new Error(msg)
}

return false
}

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