0

I have method for arrays to check if they are equal. So i want to export this method for having ability to use this method in all project. I have file A.js. How to export this method from there?

Array.prototype.equals = function(array) {
  // if the other array is a falsy value, return
  if (!array) return false

  // compare lengths - can save a lot of time
  if (this.length != array.length) return false

  for (var i = 0, l = this.length; i < l; i++) {
    // Check if we have nested arrays
    if (this[i] instanceof Array && array[i] instanceof Array) {
      // recurse into the nested arrays
      if (!this[i].equals(array[i])) return false
    } else if (this[i] != array[i]) {
      // Warning - two different object instances will never be equal: {x:20} != {x:20}
      return false
    }
  }
  return true
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, 'equals', { enumerable: false })
WhoIsDT
  • 695
  • 2
  • 9
  • 27
  • I think you got it from here https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript? A library like lodash can help you https://lodash.com/docs/#isEqual, you can import only this function so size will be small. – Miller Oct 02 '19 at 17:28
  • Not an ideal approach to take. But you can certainly do it this way. Create a file from which you would ideally export the method. However, after writing the code, don't export the function . Instead in your other files, just call it as `import './your_file_location/fileName.js';` . This would do the trick – Ritumoni Sharma Nov 12 '22 at 08:23

1 Answers1

0

It looks like you are extending prototype of an Array class/type. So it should already be available everywhere that A.js script of yours is included. No need for additional exports. If you're using some kind of "compiler" (Rollup, Webpack, etc...) that builds single JS file from separate sources, just make sure A.js is compiled in, and before other functions/code is executed.

However, it's not encouraged to extend basic types like that, because you never know if something else does not try to extend the same type with the same function name, but different results, which can be hard to debug later.

You can refactor it into stand-alone function instead. Something like this:

function isArrayEqual (a, b) {
  // if the other array is a falsy value, return
  if (!a || !b) return false
  
  // if any of them is not an Array, return
  if (!Array.isArray(a) || !Array.isArray(b)) return false

  // compare lengths - can save a lot of time
  if (a.length != b.length) return false

  for (var i = 0, l = a.length; i < l; i++) {
    // Check if we have nested arrays
    if (a[i] instanceof Array || b[i] instanceof Array) {
      // recurse into the nested arrays
      if (!isArrayEqual(a[i], b[i])) return false
    } else if (a[i] != b[i]) {
      // Warning - two different object instances will never be equal: {x:20} != {x:20}
      return false
    }
  }
  return true
}

console.log('[] vs []', isArrayEqual([], [])); // true
console.log('[1] vs []', isArrayEqual([1], [])); // false
console.log('[] vs [1]', isArrayEqual([], [1])); // false
console.log('[1] vs [1]', isArrayEqual([1], [1])); // true
console.log('[1] vs [2]', isArrayEqual([1], [2])); // false
console.log('[[1], [2]] vs [[1], [2]]', isArrayEqual([[1], [2]], [[1], [2]])); // true
console.log('[[1], [2]] vs [[1], []]', isArrayEqual([[1], [2]], [[1], []])); // false
console.log('[1, [2]] vs [1, 2]', isArrayEqual([1, [2]], [1, 2])); // false
// Code does not strict-equal so following will return true:
console.log('[1] vs ["1"]', isArrayEqual([1], ['1'])); // true!
ahwayakchih
  • 2,101
  • 19
  • 24
  • so better idea will be to make a function from that? Can you help with converting it to standalone function. I'ts a recursive func. Idea behind the func is to check if 2 arrays are equal – WhoIsDT Oct 02 '19 at 17:14
  • In your refactor `[1, [2]]` and `[1, 2]` will be equal as well – Miller Oct 02 '19 at 17:31
  • @Miller i did not change the results, original code would fail too (try `[[1, [2]]].equals([[1, 2]])`. But you're right - that's a bug. I updated answer again and fixed it, thanks :). – ahwayakchih Oct 02 '19 at 17:41
  • Yeah, i understand what you did, no blame to you :) just wanted to mention. Since starter copied this example from another thread i was suggestion to use a library, since some knowledge is required to have a bulletproof compare fn. – Miller Oct 02 '19 at 17:44
  • Yeah, using library might be a better solution in many (most?) of the cases, as it's probably a lot more tested. But if one is learning, i think it's good to try to write code to actually learn writing code, even if it's just "reinventing the wheel" :). – ahwayakchih Oct 02 '19 at 17:50
  • Of course, as you noticed, this code was just copied and pasted, so not much of writing would go there probably. Oh well... at least we fixed one bug and got an example of refactoring ;). – ahwayakchih Oct 02 '19 at 17:55
  • When learning and writing yourself i agree, was not the case though. And yes, you just did it again ;) – Miller Oct 02 '19 at 18:07