Created
October 25, 2024 10:18
-
-
Save wiiaboo/e08da3bc98df54bb04f195c638af661a to your computer and use it in GitHub Desktop.
andQueries.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
* Join an arbitrary number of encoded queries with a global AND. | |
* @param {...String[]|String} query - Zero or more encoded queries or arrays of encoded queries. Arrays are interpreted as encoded queries to be joined by OR (^NQ) | |
* @returns {String} | |
* @example | |
* andQueries('active=true', 'locked_out=false') === 'active=true^locked_out=false' | |
* andQueries('active=true^NQactive=false', 'locked_out=false') === 'active=true^locked_out=false^NQactive=false^locked_out=false' | |
* andQueries('a=b', 'd=e', ['f=g', 'h=i', 'j=k']) === 'a=b^d=e^f=g^NQa=b^d=e^h=i^NQa=b^d=e^j=k' | |
* andQueries('a=b', 'd=e', 'f=g^NQh=i^NQj=k') === 'a=b^d=e^f=g^NQa=b^d=e^h=i^NQa=b^d=e^j=k' | |
* andQueries('active=true', []) === 'active=true' | |
* andQueries('active=true^NQ', 'locked_out=false') === 'active=true^locked_out=false^NQlocked_out=false' | |
* andQueries('a=b', ['e=f', '']) === 'a=b^e=f^NQa=b' | |
*/ | |
function andQueries () { | |
function isNonEmptyString(s) { | |
return s != null && !Array.isArray(s) && String(s).trim() !== ''; | |
} | |
var queries = Array.prototype.slice.call(arguments) | |
// ignore arguments that are not non-empty string or arrays | |
.filter(function (q) { return isNonEmptyString(q) || Array.isArray(q); }, this) | |
// convert string arguments to arrays split by ORs | |
.map(function (q) { | |
var str = Array.isArray(q) ? q.join('^NQ') : q; | |
return String(str).replace(/\^EQ$/, '').split('^NQ'); | |
}) | |
// ignore empty arrays | |
.filter(function (q) { return q.length > 0; }); | |
if (!queries.length) return ''; | |
// pre-seed result with first query | |
var concat = queries.shift(); | |
queries.forEach(function (ors) { | |
var results = []; | |
ors.forEach(function (query) { | |
concat.forEach(function (cur) { | |
// filter out empty strings just before AND-joining to avoid trailing ANDs | |
results.push([cur, query].filter(isNonEmptyString).join('^')); | |
}); | |
}); | |
concat = results; | |
}); | |
return concat.join('^NQ'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment