1

Given Code

var isEmptyArray = function (array) {
   if (typeof array !== 'undefined' && array.length > 0) {
}

Usage

isEmptyArray(myArray);

Wanted Result

How can I re-write above to be able to use:

myArray.isEmptyArray();

1 Answer 1

4

Just javascript:

Array.prototype.isEmptyArray = function() {
    return this.length === 0;
}

Typescript:

interface Array<T> {
    isEmptyArray(): boolean;
}

Array.prototype.isEmptyArray = function() {
    return this.length === 0;
}

Edit

The above solution will work for all instances of Array, for example:

let a = [];
console.log(a.isEmptyArray()); // true
a.push(1);
console.log(a.isEmptyArray()); // false

You can create your own array class and then implement needed methods just there (without affecting other Array instances):

class MyArray<T> extends Array<T> {
    public isEmptyArray(): boolean {
        return this.length === 0;
    }
}

let a1 = [];
console.log(a1.isEmptyArray()); // Uncaught TypeError: a.isEmptyArray is not a function

let a2 = new MyArray<any>();
console.log(a2.isEmptyArray()); // true

This approach is good when you're using other js libraries which are not aware of the changes you've made in the Array prototype.

Sign up to request clarification or add additional context in comments.

7 Comments

It has nothing to do with Angular, it's just a matter of having the method in all array instances or just specific ones. I updated my answer.
This approach is bad because you're augmenting Array's prototype with a completely trivial operation. Surely it's more performant and equally readable to simply inline if(arr.length === 0)? If you aren't sure if arr exists, simply use if(arr && arr.length)...
@headeronly In Object Oriented, the point is to have the ability to add methods to your classes. If you check a lot whether or not an array is empty then it makes much sense to put that into a method
@NitzanTomer This is not an OO vs. functional programming issue. Mutating the prototype of built-in objects has a bad smell about it. You are modifying a standardised, well-documented API for the sake of adding a trivial helper function. It's not "your" class. See stackoverflow.com/questions/14034180/…
@headeronly It depends on the scenario. And I wrote that in my answer, if there are no scripts in your page that might get broken because of that then there's no reason why not.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.