Adding and searching for words in custom Data Structure in JavaScript


Problem

We are required to design a data structure in JavaScript that supports the following two operations −

  • addWord, which adds a word to that Data Structure (DS), we can take help of existing DS like arrays or any other DS to store this data,
  • search, which searches a literal word or a regular expression string containing lowercase letters "a-z" or "." where "." can represent any letter

For example

addWord("sir")
addWord("car")
addWord("mad")
search("hell") === false
search(".ad") === true
search("s..") === true

Example

Following is the code −

 Live Demo

class MyData{
   constructor(){
      this.arr = [];
   };
};
MyData.prototype.addWord = function (word) {
   this.arr.push(word)
};
MyData.prototype.search = function (word) {
   let reg = new RegExp('^'+word+'$');
   return !!this.arr.find(el => reg.test(el));
};
const data = new MyData();
data.addWord('sir');
data.addWord('car');
data.addWord('mad');
console.log(data.search('hell'));
console.log(data.search('.ad'));
console.log(data.search('s..'));

Output

Following is the console output −

false
true
true

Updated on: 19-Apr-2021

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements