Swift's String.padding in TypeScript

How to use

Install via yarn add locutus and import: import { padding } from 'locutus/swift/String/padding'.

Or with CommonJS: const { padding } = require('locutus/swift/String/padding')

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
1padding('abc', 8, 'xy', 0)'abcxyxyx'
2padding('abcdef', 4, 'xy', 0)'abcd'
3padding('go', 7, '123', 1)'go23123'

Notes

  • Mirrors Swift’s padding(toLength:withPad:startingAt:) behavior for truncation and pad-fill.

Here's what our current TypeScript equivalent to Swift's String.padding looks like.

export function padding(str: string, toLength: number, withPad: string = ' ', startingAt: number = 0): string {
// discuss at: https://locutus.io/swift/String/padding/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Mirrors Swift's padding(toLength:withPad:startingAt:) behavior for truncation and pad-fill.
// example 1: padding('abc', 8, 'xy', 0)
// returns 1: 'abcxyxyx'
// example 2: padding('abcdef', 4, 'xy', 0)
// returns 2: 'abcd'
// example 3: padding('go', 7, '123', 1)
// returns 3: 'go23123'

const source = String(str)
const targetLength = Math.trunc(Number(toLength))
const pad = String(withPad)

if (!Number.isFinite(targetLength) || targetLength <= 0) {
return ''
}
if (source.length >= targetLength) {
return source.slice(0, targetLength)
}
if (pad.length === 0) {
return source
}

const start = Math.max(0, Math.trunc(Number(startingAt))) % pad.length
const needed = targetLength - source.length

let repeated = ''
while (repeated.length < needed + start) {
repeated += pad
}

return source + repeated.slice(start, start + needed)
}

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


We have 8 Swift functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

  • Get inspiration from the Swift documentation.
  • Click "New file" in the appropriate folder on GitHub. This will fork the project to your account, directly add the file to it, and send a Pull Request to us.

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Swift String functions


Star