Skip to content

fix(utils): pad() throws RangeError when target length is smaller than string length #39160

@sahillllllllll-bit

Description

@sahillllllllll-bit

Problem

The utility function pad() in stringUtils.ts does not handle cases where the requested length is smaller than the original string length.

Current implementation:

padlen = length - str.length;
return str + padStr.repeat(padlen);

If length < str.length, padlen becomes negative and String.prototype.repeat() throws:

RangeError: Invalid count value

This causes a runtime exception inside the server environment.

steps to Reproduce

Call the function:

pad("rocket", 3)

Output:

RangeError: Invalid count value

Expected behavior

When the desired length is smaller than the string length, the function should safely return the original string instead of throwing an exception.

Proposed Solution

Clamp the padding length to zero before calling repeat():

padlen = Math.max(0, length - str.length);

Apply this to all branches (right, left, both).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions