Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

vsemozhetbyt
Copy link
Contributor

@vsemozhetbyt vsemozhetbyt commented Jan 7, 2017

  1. Use object shorthand notation.
  2. Remove default constructors (see http://eslint.org/docs/rules/no-useless-constructor).
  3. Use functional Array methods instead of cycles and intermediate structures.

The third change also excludes hidden type coercion from array elements comparing.

Using the previous example:

/******************************************************************************/
'use strict';
/******************************************************************************/
class SuperArray extends Array {
  constructor(...args) {
    super(...args);
  }

  diff(comparisonArray) {
    var values = [];
    var hash = {};

    for (var i of comparisonArray) {
      hash[i] = true;
    }

    for (var i of this) {
      if (!hash[i]) {
        values.push(i);
      }
    }

    return values;
  }
}

const sa = new SuperArray(1, 2, 3);
console.log(sa.diff(['1', '2', 3]));
[]

Using the new example:

class SuperArray extends Array {
  diff(comparisonArray) {
    return this.filter(elem => !comparisonArray.includes(elem));
  }
}

const sa = new SuperArray(1, 2, 3);
console.log(sa.diff(['1', '2', 3]));
SuperArray [ 1, 2 ]

As additional feature, you can use .diff() chaining here.

@vsemozhetbyt
Copy link
Contributor Author

vsemozhetbyt commented Jan 11, 2017

It partly intersects with #114. The conflicts will be resolved if needed.

@ryanmcdermott ryanmcdermott merged commit cd50889 into ryanmcdermott:master Jan 12, 2017
@ryanmcdermott
Copy link
Owner

Much cleaner! I'm not sure how includes operates under the hood. Could go from being O(n) to O(n^2) as the outer loop goes through each item in the SuperArray and the inner loop goes through each item in the comparisonArray. Since it's just example code, and I don't actually know how that built-in array method works, this is much better for a clean example!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants