Skip to content

Commit

Permalink
Merge pull request #3 from MikeIbberson/feat/array-or
Browse files Browse the repository at this point in the history
[FEATURE] Array as serialized string
  • Loading branch information
MikeIbberson committed Mar 11, 2020
2 parents ce916c8 + e5aa40f commit 3e794a0
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 10 deletions.
2 changes: 1 addition & 1 deletion lib/__tests__/comparison.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const sift = require('sift').default;
const Comparison = require('..');

const exp = [
'foo=bar',
'foo=bar,quuz',
'age<30',
'age>=21',
'language=EN',
Expand Down
19 changes: 12 additions & 7 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const {
isLessThanOrEqualTo,
isEmpty,
cast,
isSerialized,
} = require('./utils');

const ops = {
Expand All @@ -21,6 +22,9 @@ const ops = {
};

const getAssignment = {
'in': (v) => ({
$in: v,
}),
'equals': cast,
'isEmpty': cast,
'isLessThan': (v) => ({
Expand Down Expand Up @@ -78,13 +82,14 @@ class Comparison {

query() {
return {
$and: this.eligible.reduce(
(a, [key, value, fn]) =>
a.concat({
[key]: getAssignment[fn.name](value),
}),
[],
),
$and: this.eligible.reduce((a, [key, value, fn]) => {
const v = isSerialized(value) ? value.split(',') : value;
const name = Array.isArray(v) ? 'in' : fn.name;

return a.concat({
[key]: getAssignment[name](v),
});
}, []),
};
}

Expand Down
8 changes: 7 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,12 @@ const runCompare = (a, b, locale) =>
});

const equals = (a, b, locale) => {
const comp = (v) => runCompare(a, v, locale) === 0;
if (b === '*') return a !== '' && a !== undefined && a !== null;
if (typeof b === 'string' && b.includes(','))
return b.split(',').some(comp);

return runCompare(a, b, locale) === 0;
return comp(b);
};

const doesNotEqual = (a, b, locale) => runCompare(a, b, locale) !== 0;
Expand Down Expand Up @@ -104,6 +107,8 @@ const cast = (v) => {
const isEmpty = (v) =>
v === undefined || v === null || v === 'undefined' || v === 'null';

const isSerialized = (v) => typeof v === 'string' && v.includes(',');

module.exports = {
equals,
doesNotEqual,
Expand All @@ -114,4 +119,5 @@ module.exports = {
isEmpty,
validate,
cast,
isSerialized,
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "comparisons",
"version": "2.2.0",
"version": "2.2.1",
"main": "lib/index.js",
"license": "MIT",
"jest": {
Expand Down

0 comments on commit 3e794a0

Please sign in to comment.