Sato
Sato

Reputation: 8602

Is there a single function to check an array contains another array?

[1,2,3].CONTAINS([1,2]) ==> true
[1,2,3].CONTAINS([1,2,3,4]) ==> false

or

{a:1,b:2,c:3}.HASKEYS([a,b]) ==> true
{a:1,b:2,c:3}.HASKEYS([a,b,c,d]) ==> false

Is there a single function to check an array contains another array?

Upvotes: 2

Views: 86

Answers (1)

Blender
Blender

Reputation: 298196

No, but you can make one:

Array.prototype.contains = function(other) {
    for (var i = 0; i < other.length; i++) {
        if (this.indexOf(other[i]) === -1) return false;
    }

    return true;
}

And if order matters:

Array.prototype.contains = function(other) {
    var broken;

    if (!other.length) return true;

    for (var i = 0; i < this.length - other.length + 1; i++) {
        broken = false;

        for (var j = 0; j < other.length; j++) {
            if (this[i + j] !== other[j]) {
                broken = true;
                break;
            }
        }

        if (!broken) return true;
    }

    return false;
}

The other function is similar, so I'll leave it to you to finish:

Object.prototype.has_keys = function(keys) {
    ...
}

Upvotes: 4

Related Questions