PHP's vprintf in TypeScript

How to use

Install via yarn add locutus and import: import { vprintf } from 'locutus/php/strings/vprintf'.

Or with CommonJS: const { vprintf } = require('locutus/php/strings/vprintf')

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
1vprintf("%01.2f", 123.1)6

Dependencies

This function uses the following Locutus functions:

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

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

type PrintfValue = PhpRuntimeValue

export function vprintf(format: string, args: PrintfValue[]): number

export function vprintf(format: string, ...args: PrintfValue[]): number

export function vprintf(format: string, ...restArgs: [PrintfValue[]] | PrintfValue[]): number {
// discuss at: https://locutus.io/php/vprintf/
// original by: Ash Searle (https://hexmen.com/blog/)
// improved by: Michael White (https://getsprink.com)
// reimplemented by: Brett Zamir (https://brett-zamir.me)
// example 1: vprintf("%01.2f", 123.1)
// returns 1: 6

let values: PrintfValue[] = []
if (restArgs.length === 1 && Array.isArray(restArgs[0])) {
values = restArgs[0]
} else {
values = restArgs
}
const ret = sprintf(format, ...values)
if (ret === false) {
return 0
}
echo(ret)

return ret.length
}

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 strings functions


Star