Reputation: 15702
var isEmptyArray = function (array) {
if (typeof array !== 'undefined' && array.length > 0) {
}
isEmptyArray(myArray);
How can I re-write above to be able to use:
myArray.isEmptyArray();
Upvotes: 1
Views: 61
Reputation: 164137
Just javascript:
Array.prototype.isEmptyArray = function() {
return this.length === 0;
}
Typescript:
interface Array<T> {
isEmptyArray(): boolean;
}
Array.prototype.isEmptyArray = function() {
return this.length === 0;
}
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.
Upvotes: 4