Skip to content

Instantly share code, notes, and snippets.

@pvdz
Forked from binarymax/LICENSE.txt
Created September 8, 2011 07:17
Show Gist options
  • Save pvdz/1202842 to your computer and use it in GitHub Desktop.
Save pvdz/1202842 to your computer and use it in GitHub Desktop.
isSubset
function(
A, //The Set array
B //The Subset array to check
) {
for(
var // (redeclaration of A and B is ignored so is ok, else you'll lose extra bytes when moving their init out of the var decl)
A=A.slice().sort(), //copy and sort set array
B=B.slice().sort(), //copy and sort subset array
a=A.length,
b=B.length;
a&&b;) //go until one array hits the end
if(A[--a]==B[b-1])--b; // if element found from subset in set, inc subset index
return !b //returns true if every subset element in B exists in A
}
function(a,b){for(var a=a.slice().sort(),b=b.slice().sort(),c=a.length,d=b.length;c&&d;)if(a[--c]==b[d-1])--d;return!d}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Max Irwin http://www.binarymax.com/
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "isSubset",
"description": "Checks if array 'u' is subset of array 'S'.",
"keywords": [
"subset",
"set"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>true,false,true,true</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var f = function(a,b){for(var a=a.slice().sort(),b=b.slice().sort(),c=a.length,d=b.length;c&&d;)if(a[--c]==b[d-1])--d;return!d}
var a = ["apples","oranges","bananas","grapes","strawberries"];
var b = ["strawberries","bananas"];
var c = ["strawberries","kiwis"];
var d = [];
var r1 = f(a,b); // b is a subset of a
var r2 = f(a,c); // c is not a subset of a
var r3 = f(a,d); // The empty set is a subset
var r4 = f(a,a); // A set is a subset of itself
var r5 = f(a,e); // Just checking first and last element
document.getElementById( "ret" ).innerHTML = r1 + ',' + r2 + ',' + r3 + ',' + r4 + ',' + r5;
</script>
@maettig
Copy link

maettig commented Dec 1, 2011

One of my favorite 140byt.es snippets. Very clever. Using && instead if if it's possible to save 2 bytes. And the line var e = ["strawberries","apples"]; is missing in your test.

function(a,b){for(var a=a.slice().sort(),b=b.slice().sort(),c=a.length,d=b.length;c&&d;)a[--c]==b[d-1]&&--d;return!d}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment