1

So, the JavaScript implementation that NetSuite employs for its server-side processing lacks the Array.find() method, as from what I found because it uses ECMAScript 5.1, and the method was defined in ES6 (TypeError: Cannot find function find in object), so that has limited some other options for handling this. So I wanted to define a replacement in my library file that would also be as efficient as possible (not naming them "find" to prevent overriding the default function in case my library is loaded into a browser). I have the following two versions:

Version #1

Array.prototype.altFind = function (func) {
    if (func == null) { return null; }
    for (var i = 0; i < this.length; i++) {
        if (func(this[i])) {
            return this[i];
        }
    }

    return null;
}

Version #2

Object.defineProperty(Array.prototype, 'altFind',
    {
            value: function (predicate) {
                if (this == null) {
                    throw new TypeError('"this" is null or not defined');
                }
                if (predicate == null)) {
                    throw new TypeError('predicate is null or not defined');
                }
                var o = Object(this);
                var len = o.length >>> 0;
                if (typeof predicate !== 'function') {
                    throw new TypeError('predicate must be a function');
                }
                var thisArg = arguments[1];
                var k = 0;
                while (k < len) {
                    var kValue = o[k];
                    if (predicate.call(thisArg, kValue, k, o)) { return kValue; }
                    k++;
                }
                return undefined;
            }
        ,   configurable: true
        ,   writable: true
    }
);

(NOTE: version #2 was found at https://netsuitehub.com/forums/topic/adding-modern-functionality-to-array-object-find-findindex-in-your-server-side-suitescripts/ to give them credit)

I'm not good at determining overall code efficiency, so would anyone be able to tell me which version would be the most ideal? Or if there's a way to make either of them more efficient?

Michael McCauley
  • 853
  • 1
  • 12
  • 37
  • 3
    I'd recommend you don't write it from scratch, but rather use the "official" polyfill here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find or a library like core.js – georg Nov 05 '19 at 19:22
  • 3
    FYI, SuiteScript 2.1 is now available in beta, and it supports ECMAScript 2018. You can opt in to use version 2.1 by using the /**@NApiVersion 2.1 */ tag in the JSDoc comment block of your script. – Krypton Nov 05 '19 at 19:52
  • @georg -- ok, it looks like my "version #2" is the polyfill, but without checking to see if "find" is already defined in the prototype. I'll just update my library file to make that check. – Michael McCauley Nov 05 '19 at 22:13

0 Answers0