I came across a rather peculiar implementation of a string repeat function for JavaScript.

There's a built-in for this since ES2015, and prior to that, the following was a common idom:

> str = "x"
> count = 3
> out = (new Array(count + 1).join(str)

But, an MDN contributor thought - we can optimize this! Can you figure out how and why it works?


@krinkle it doubles the string until its long enough, then truncates it out the exact length.

The log based math stuff is slow though. Just check the length after each doubling, that'll do. Or calculate the log based on the position of the highest 1 bit.

@krinkle if we assume that string concatenation is O(n+m), I think the naive approach is O(n²), while the smart one is O(n). For a large repetition count, that may be worthwhile I guess.

Sign in to participate in the conversation
Mastodon for Tech Folks

This Mastodon instance is for people interested in technology. Discussions aren't limited to technology, because tech folks shouldn't be limited to technology either!