mikemclin / angular-acl

Role-based permissions for AngularJS
196 stars 49 forks source link

Update IndexOf prototype check #3

Closed tplaindoux closed 9 years ago

tplaindoux commented 9 years ago

From your comment, this link http://stackoverflow.com/questions/1181575/javascript-determine-whether-an-array-contains-a-value/1181586#1181586

now provide a better solution:

Edit after a long time: It's best not to patch the prototype of native primitives in JavaScript. A better way:

var indexOf = function(needle) {
    if(typeof Array.prototype.indexOf === 'function') {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function(needle) {
            var i = -1, index = -1;

            for(i = 0; i < this.length; i++) {
                if(this[i] === needle) {
                    index = i;
                    break;
                }
            }

            return index;
        };
    }

    return indexOf.call(this, needle);
};
You can use it like this:

var myArray = [0,1,2],
    needle = 1,
    index = indexOf.call(myArray, needle); // 1
mikemclin commented 9 years ago

Thanks for your input, and checking out the source :smile:

Personally, I don't mind the polyfill method. I'd prefer to code in a modern native syntax, instead of creating helper functions that need to be remembered and learned.

Mozilla Developer Network suggests a polyfill as a fallback solution too, although it contains more complexity than what was required for this package, which is why I chose a simpler polyfill.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf