 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements
 