Indexing Typescript Todo Entities with Lunr

Image by Chil Vera from Pixabay

Scenario

interface Todo {
gid?: string;
id?: string;
complete: boolean;
title: string;
}
const TODO_ID_1 = '1';
const TODO_ID_2 = '2';
const TODO1: Todo = {
id: TODO_ID_1,
complete: false,
title: 'You complete me!'
};
const TODO2: Todo = {
id: TODO_ID_2,
complete: true,
title: 'You completed me!'
};
let todos: Todo[] = [TODO1, TODO2];

Approach

function initializeSearchIndex(todos: Todo[]): lunr.Index {
const idx: lunr.Index = lunr(function () {
this.field('complete');
this.field('title');
todos.forEach((todo) => {
this.add(todo);
});
});
return idx;
}
const idx = initializeSearchIndex(todos);
const idxResult: lunr.Index.Result[] = idx.search('false');
[
{
"ref": "1",
"score": 0.693,
"matchData": {
"metadata": {
"fals": {
"complete": {}
}
}
}
}
]
function search(query: string) {
const results = idx.search(query);
return results.map((result) => {
return todos.find((todo) => result.ref === todo.id);
});
}
const searchResult = search('false');
//console.log(searchResult);
[
{
"id": "1",
"complete": false,
"title": "Firefly Semantics Slice Rocks!!"
}
]

Demo

--

--

Founder of Firefly Semantics Corporation

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store