Created
March 2, 2018 17:19
-
-
Save GreggSetzer/13d97d6d8d50426957aca4bb12db6dcd to your computer and use it in GitHub Desktop.
Javascript Interview Question: Revealing Module Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Use the module pattern to group together similar methods such as database services. | |
In the example below, the ItemDao (Data Access Object) simulates several functions | |
that interact with a database. | |
1. Use modules to encapsulate related functionality. | |
2. A module pattern at its core is an object literal. | |
3. When using the module in code, call the functions using the key/value syntax. | |
For example: itemDao.findOne(1); | |
4. Wrap the object into a function to create a closure for private variables. Examples | |
of private variables would include database credentials, connection string values, etc. | |
These are private variables and are not accessible from the code. | |
5. Keep in mind, a difference between the module pattern and the constructor pattern is that | |
we generally will have only one instance of the service. We will reuse it, where as, the | |
constructor pattern creates new instances of objects. | |
*/ | |
var ItemDao = function() { | |
let db = { | |
1: { name: 'Coffee', price: 1.50, type: 'beverage' }, | |
2: { name: 'Espresso', price: 2.25, type: 'beverage' }, | |
3: { name: 'Latte', price: 3.50, type: 'beverage' }, | |
4: { name: 'Biscotti', price: 3.50, type: 'food' }, | |
5: { name: 'Muffin', price: 3.50, type: 'food' } | |
} | |
function findOne(id) { | |
return db[id]; | |
} | |
function findByType(type) { | |
let resultSet = []; | |
for (let key in db) { | |
if (db[key].type === type) { | |
resultSet.push(db[key]); | |
} | |
} | |
return resultSet; | |
} | |
//Our public interface for ItemDao. | |
return { | |
findOne, | |
findByType | |
} | |
} | |
let itemDao = new ItemDao(); | |
let item = itemDao.findOne(2); | |
console.log(`Your ${item.name} will cost $${item.price}`); | |
let items = itemDao.findByType('food'); | |
console.log(items); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment