cluster1
cluster1

Reputation: 5674

JavaScript repeat-Polyfill: Does these code structure make sense?

I've tried to understand the code of the String.prototype.repeat()-polyfill.

Complete code here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

I ask myself if the following part is logical:

    // Tries to cast the parameter 'count' to a number.
    count = +count;

    // If the cast fails ('count' has become NaN) then
    // assign 0 to the parameter-variable.
    if (count != count) {
      count = 0;
    }

    // Does some more checks with the parameter ...
    if (count < 0) {
      throw new RangeError('repeat count must be non-negative');
    }
    if (count == Infinity) {
      throw new RangeError('repeat count must be less than infinity');
    }
    // End of checks ...

    // Rounds the parameter to next lower integer.
    count = Math.floor(count);

    // Checks if count is 0. In that case: Terminate 
    // the function / Return an empty string.
    if (str.length == 0 || count == 0) {
      return '';
    }

Why not terminating after the cast fails (at the top)?

Instead assigning 0, run checks, checking against 0. And if that state is true THEN terminating.

Makes no sense to me.

Is there anything which I haven't understood?

Upvotes: 2

Views: 56

Answers (1)

Martin Chaov
Martin Chaov

Reputation: 864

Because this polyfill needs to implement the same behavior as in the specs. Spec say if value is less than zero you should throw error.

Also, casting to number at the start is fine, but can directly call this function with invalid number like so:

var string = 'abc';
string.repeat(-1); // throws range error

Upvotes: 1

Related Questions