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?