#813 enhancement
Yaffle

Array#flatten performance

Reported by Yaffle | September 29th, 2009 @ 01:56 PM | in 1.7

Array#flatten uses Array#concat:

"a.concat(b)" has complexity O(a.length+b.length) "Array.prototype.push.apply(a, b)" has complexity O(b.length) (in good case) so using "push" instead of "concat" may be better

  // old
  function flatten() {
    return this.inject([], function(array, value) {
      if (Object.isArray(value))
        return array.concat(value.flatten());
      array.push(value);
      return array;
    });
  }
  // new
  function flatten() {
    return this.inject([], function(array, value) {
      if (Object.isArray(value)) {
        Array.prototype.push.apply(array, value.flatten());
      } else {
        array.push(value);
      }
      return array;
    });
  };

or may be:

  Array.prototype.flatten =  function () {

return Array.prototype.concat.apply([], this.map(function(value){
  return Object.isArray(value)? value.flatten(): value;
}));



};

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile ยป

The Prototype JavaScript library.

Shared Ticket Bins

Attachments

Pages