From 1ad9b82631de298edd94f3ad256dcb233c384a16 Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Mon, 4 Jul 2022 11:31:39 +0200 Subject: [PATCH] Implemented array query --- packages/plugs/query/engine.test.ts | 24 +++++++++++++++++++++++- packages/plugs/query/engine.ts | 14 +++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/packages/plugs/query/engine.test.ts b/packages/plugs/query/engine.test.ts index 211044e..dfed8c3 100644 --- a/packages/plugs/query/engine.test.ts +++ b/packages/plugs/query/engine.test.ts @@ -68,7 +68,7 @@ test("Test parser", () => { }); }); -test("Test performing the queries", () => { +test("Test applyQuery", () => { let data: any[] = [ { name: "interview/My Interview", lastModified: 1 }, { name: "interview/My Interview 2", lastModified: 2 }, @@ -116,3 +116,25 @@ test("Test performing the queries", () => { applyQuery(parseQuery(`page where name in ["Pete"] select name`), data) ).toStrictEqual([{ name: "Pete" }]); }); + +test("Test applyQuery with multi value", () => { + let data: any[] = [ + { name: "Pete", children: ["John", "Angie"] }, + { name: "Angie", children: ["Angie"] }, + { name: "Steve" }, + ]; + + expect( + applyQuery(parseQuery(`page where children = "Angie"`), data) + ).toStrictEqual([ + { name: "Pete", children: ["John", "Angie"] }, + { name: "Angie", children: ["Angie"] }, + ]); + + expect( + applyQuery(parseQuery(`page where children = ["Angie", "John"]`), data) + ).toStrictEqual([ + { name: "Pete", children: ["John", "Angie"] }, + { name: "Angie", children: ["Angie"] }, + ]); +}); diff --git a/packages/plugs/query/engine.ts b/packages/plugs/query/engine.ts index 0ca3055..7e01c50 100644 --- a/packages/plugs/query/engine.ts +++ b/packages/plugs/query/engine.ts @@ -135,7 +135,19 @@ export function applyQuery(parsedQuery: ParsedQuery, records: T[]): T[] { for (let { op, prop, value } of parsedQuery.filter) { switch (op) { case "=": - if (!(recordAny[prop] == value)) { + const recordPropVal = recordAny[prop]; + if (Array.isArray(recordPropVal) && !Array.isArray(value)) { + // Record property is an array, and value is a scalar: find the value in the array + if (!recordPropVal.includes(value)) { + continue recordLoop; + } + } else if (Array.isArray(recordPropVal) && Array.isArray(value)) { + // Record property is an array, and value is an array: find the value in the array + if (!recordPropVal.some((v) => value.includes(v))) { + continue recordLoop; + } + } else if (!(recordPropVal == value)) { + // Both are scalars: exact value continue recordLoop; } break;