Description

You’re building a mini in-memory search system that can store categorized data — such as Books, Movies, or Songs.
Each category can have multiple items, and you should be able to filter and sort those items dynamically.


Your goal is to design a class that supports adding documents and querying them efficiently — all in memory.


Your Task

Implement a class InMemorySearch that supports two methods:

addDocuments(itemName, ...items)

  • Adds one or more items (objects) to the given category (itemName).
  • If the category doesn’t exist yet, create it automatically.

search(itemName, filterFunction, sortCondition)

  • Returns all items under the given category that satisfy the filterFunction.
  • If no such category exists, return an empty array.
  • If a sortCondition object is provided with { key, asc }, sort results:
    • Ascending order if asc: true
    • Descending order if asc: false

Method

Method

Description

addDocuments(itemName, ...items)

Adds documents under a category name

search(itemName, filterFunction, sortCondition)

Filters and optionally sorts items under the given category


Example

const library = new InMemorySearch();

library.addDocuments(
"Books",
{ title: "The Alchemist", rating: 4.7, year: 1988 },
{ title: "Atomic Habits", rating: 4.9, year: 2018 },
{ title: "Deep Work", rating: 4.8, year: 2016 },
{ title: "The Subtle Art of Not Giving a F*ck", rating: 4.3, year: 2016 }
);

console.log(
library.search("Books", (b) => b.rating > 4.5, { key: "year", asc: true })
);

Expected Output

[
{ title: "The Alchemist", rating: 4.7, year: 1988 },
{ title: "Deep Work", rating: 4.8, year: 2016 },
{ title: "Atomic Habits", rating: 4.9, year: 2018 }
]

Expected Behavior

✅ Stores categorized data correctly
✅ Filters results based on condition
✅ Sorts by key in ascending/descending order
✅ Returns [] for missing categories
✅ Handles multiple additions to the same category