Skip to content

Commit

Permalink
moved the code of search-compile.js to search.js
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarotero committed Mar 14, 2021
1 parent fab45cf commit 2382207
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 60 deletions.
58 changes: 0 additions & 58 deletions helpers/search-compiler.js

This file was deleted.

61 changes: 59 additions & 2 deletions helpers/search.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { compileFilter, compileSort } from "./search-compiler.js";

export default class Search {
#site = null;
#cache = null;
Expand Down Expand Up @@ -102,3 +100,62 @@ function buildFilter(query) {

return compileFilter(filter);
}

function compileFilter(query) {
const filters = [];
const args = [];

Object.keys(query).forEach((key, index) => {
const value = `value${index}`;
filters.push(compileCondition(key, value));
args.push(value);
});

args.push(`return (page) => ${filters.join(" && ")};`);

const factory = new Function(...args);

return factory(...Object.values(query));
}

function compileSort(path) {
path = path.replaceAll(".", "?.");

return new Function("a", "b", `return (a.${path} < b.${path}) ? -1 : 1`);
}

function compileCondition(key, value) {
let [path, operator] = key.trim().split(" ");

path = path.replaceAll(".", "?.");

if (!operator || operator === "=") {
return `page.${path} === ${value}`;
}

if (operator === "!=") {
return `page.${path} !== ${value}`;
}

if (operator === "^=") {
return `page.${path}?.startsWith(${value})`;
}

if (operator === "$=") {
return `page.${path}?.endsWith(${value})`;
}

if (operator === "~=") {
return `page.${path}?.includes(${value})`;
}

if (operator === "ALL") {
return `${value}.every((i) => page.${path}?.includes(i))`;
}

if (operator === "SOME") {
return `${value}.some((i) => page.${path}?.includes(i))`;
}

throw new Error(`Invalid conditional operator ${operator}`);
}

0 comments on commit 2382207

Please sign in to comment.