├── Section 5 ├── code_5.3 │ ├── EventBus.js │ ├── package.json │ ├── Store.js │ ├── app.js │ ├── Topic.js │ └── User.js ├── code_5.2 │ ├── Command.js │ ├── Invoker.js │ ├── package.json │ ├── app.js │ ├── View.js │ ├── Post.js │ ├── Update.js │ ├── Database.js │ └── dbs.json ├── code_5.5 │ ├── app.js │ ├── Chase.js │ └── Bank.js ├── code_5.1 │ ├── Payment.js │ ├── Bank.js │ ├── app.js │ ├── Chase.js │ └── Citibank.js └── code_5.4 │ ├── app.js │ └── Middleware.js ├── Section 3 ├── code_3.2 │ ├── console-logger │ │ └── index.js │ ├── file-logger │ │ ├── index.js │ │ └── activity.log │ ├── app.js │ └── Bank.js └── code_3.1 │ ├── classes │ ├── app.js │ └── Bank.js │ └── modules │ ├── app.js │ └── Bank.js ├── Section 6 ├── Code 6.2 │ ├── Rabbit.js │ ├── package.json │ ├── Subscriber.js │ └── Publisher.js └── code_6.1 │ ├── app.js │ ├── package.json │ ├── Server.js │ └── Client.js ├── Section 1 ├── code_1.3 │ ├── iPhoneXR.js │ ├── iPhoneXS.js │ ├── iPhoneXSMax.js │ ├── app.js │ ├── iPhoneFactory.js │ └── Phone.js ├── code_1.4 │ ├── pizza │ │ ├── App.js │ │ └── Pizza.js │ └── signup │ │ ├── App.js │ │ ├── Signup.js │ │ ├── User.js │ │ ├── SignupBuilder.js │ │ └── UserPref.js └── code_1.2 │ ├── Singleton_Object │ ├── App.js │ └── CashRegister.js │ └── Singleton_Class │ ├── Game.js │ ├── Player.js │ ├── App.js │ └── Scoreboard.js ├── Section 4 ├── code_4.4 │ ├── Item.js │ ├── Laptop.js │ ├── MobilePhone.js │ ├── Catalog.js │ └── app.js ├── code_4.3 │ ├── Class │ │ ├── app.js │ │ ├── package.json │ │ ├── CurrencyConverter.js │ │ └── dist │ │ │ ├── app.map │ │ │ └── app.js │ └── Function │ │ ├── app.js │ │ ├── package.json │ │ └── CurrencyConverter.js ├── code_4.1 │ ├── Vault │ │ ├── package.json │ │ ├── app.js │ │ └── Vault.js │ └── Reactive │ │ └── Reactive.js └── code_4.2 │ ├── package.json │ ├── Db.js │ ├── app.js │ ├── dbs.json │ └── LokiAdapter.js ├── Section 2 ├── code_2.4 │ ├── fruit-salad │ │ └── fruitSalad.js │ └── async-generators │ │ ├── app.js │ │ ├── inbox │ │ ├── Writing_a_Book.txt │ │ ├── The_Sandy_Cat.txt │ │ └── The_Wooden_Doll.txt │ │ └── outbox │ │ ├── Writing_a_Book.txt │ │ ├── The_Sandy_Cat.txt │ │ └── The_Wooden_Doll.txt ├── code_2.1 │ ├── app.js │ ├── inbox │ │ ├── Writing_a_Book.txt │ │ ├── The_Sandy_Cat.txt │ │ └── The_Wooden_Doll.txt │ └── outbox │ │ ├── Writing_a_Book.txt │ │ ├── The_Sandy_Cat.txt │ │ └── The_Wooden_Doll.txt ├── code_2.2 │ ├── app.js │ ├── inbox │ │ ├── Writing_a_Book.txt │ │ ├── The_Sandy_Cat.txt │ │ └── The_Wooden_Doll.txt │ └── outbox │ │ ├── Writing_a_Book.txt │ │ ├── The_Sandy_Cat.txt │ │ └── The_Wooden_Doll.txt └── code_2.3 │ ├── app.js │ ├── inbox │ ├── Writing_a_Book.txt │ ├── The_Sandy_Cat.txt │ └── The_Wooden_Doll.txt │ └── outbox │ ├── Writing_a_Book.txt │ ├── The_Sandy_Cat.txt │ └── The_Wooden_Doll.txt ├── LICENSE └── README.md /Section 5/code_5.3/EventBus.js: -------------------------------------------------------------------------------- 1 | const {EventEmitter} = require("events"); 2 | module.exports = new EventEmitter(); 3 | -------------------------------------------------------------------------------- /Section 5/code_5.2/Command.js: -------------------------------------------------------------------------------- 1 | class Command { 2 | execute() {} 3 | undo() {} 4 | } 5 | 6 | module.exports = Command; 7 | -------------------------------------------------------------------------------- /Section 3/code_3.2/console-logger/index.js: -------------------------------------------------------------------------------- 1 | const write = log => console.log(`${new Date()} : ${log}`); 2 | 3 | module.exports = { 4 | write 5 | } -------------------------------------------------------------------------------- /Section 6/Code 6.2/Rabbit.js: -------------------------------------------------------------------------------- 1 | const amqp = require("amqplib"); 2 | const amqpUri = "amqp://localhost"; 3 | module.exports = () => amqp.connect(amqpUri); 4 | -------------------------------------------------------------------------------- /Section 3/code_3.1/classes/app.js: -------------------------------------------------------------------------------- 1 | const Bank = require("./Bank"); 2 | const user1 = "John Doe"; 3 | 4 | Bank.createAccount(user1); 5 | Bank.credit(user1, 20); 6 | Bank.credit(user1, 33); 7 | console.log(Bank.getFunds(user1)); -------------------------------------------------------------------------------- /Section 5/code_5.5/app.js: -------------------------------------------------------------------------------- 1 | const Chase = require("./Chase"); 2 | const bank = new Chase(); 3 | 4 | bank.createAccount("John Doe", 1000); 5 | bank.credit("John Doe", 500); 6 | bank.debit("John Doe", 250); 7 | bank.view("John Doe"); 8 | -------------------------------------------------------------------------------- /Section 5/code_5.1/Payment.js: -------------------------------------------------------------------------------- 1 | // Context 2 | class Payment { 3 | pay(processor) { 4 | return processor.pay(); 5 | } 6 | refund(processor) { 7 | return processor.refund(); 8 | } 9 | } 10 | 11 | module.exports = Payment; 12 | -------------------------------------------------------------------------------- /Section 3/code_3.1/modules/app.js: -------------------------------------------------------------------------------- 1 | const Bank = require("./Bank"); 2 | const user1 = "John Doe"; 3 | 4 | Bank.createAccount(user1); 5 | Bank.credit(user1, 100); 6 | Bank.debit(user1, 25); 7 | console.log(Bank.getFunds(user1)); 8 | console.log(Bank._accounts); -------------------------------------------------------------------------------- /Section 1/code_1.3/iPhoneXR.js: -------------------------------------------------------------------------------- 1 | const Phone = require('./Phone'); 2 | 3 | class iPhoneXR { 4 | constructor(serialNum) { 5 | return new Phone(serialNum, 'iPhone Xr', 'A12 Bionic', '3 Gb', 75.7, 150.9, 8.3, '828 x 1792'); 6 | } 7 | } 8 | 9 | module.exports = iPhoneXR; -------------------------------------------------------------------------------- /Section 1/code_1.3/iPhoneXS.js: -------------------------------------------------------------------------------- 1 | const Phone = require('./Phone'); 2 | 3 | class iPhoneXS { 4 | constructor(serialNum) { 5 | return new Phone(serialNum, 'iPhone Xs', 'A12 Bionic', '4 Gb', 70.9, 143.6, 7.7, '1125 x 2436'); 6 | } 7 | } 8 | 9 | module.exports = iPhoneXS; -------------------------------------------------------------------------------- /Section 1/code_1.3/iPhoneXSMax.js: -------------------------------------------------------------------------------- 1 | const Phone = require('./Phone'); 2 | 3 | class iPhoneXSMax { 4 | constructor(serialNum) { 5 | return new Phone(serialNum, 'iPhone Xs Max', 'A12 Bionic', '4 Gb', 77.4, 157.5, 7.9, '1242 x 2688'); 6 | } 7 | } 8 | 9 | module.exports = iPhoneXSMax; -------------------------------------------------------------------------------- /Section 1/code_1.4/pizza/App.js: -------------------------------------------------------------------------------- 1 | const Pizza = require('./Pizza'); 2 | const pepperoni = new Pizza(); 3 | 4 | pepperoni.setBase('Whole Wheat'); 5 | pepperoni.setSauce('Tomato Basil'); 6 | pepperoni.setCheese('Smoked Mozzarella'); 7 | pepperoni.setToppings(['Pepperoni', 'Basil']); 8 | 9 | pepperoni.bake(); -------------------------------------------------------------------------------- /Section 4/code_4.4/Item.js: -------------------------------------------------------------------------------- 1 | class Item { 2 | constructor(name, type) { 3 | this.name = name; 4 | this.type = type; 5 | } 6 | getType() { 7 | return this.type; 8 | } 9 | getName() { 10 | return this.name; 11 | } 12 | getDetails() {} 13 | } 14 | 15 | module.exports = Item; -------------------------------------------------------------------------------- /Section 4/code_4.3/Class/app.js: -------------------------------------------------------------------------------- 1 | import CurrencyConverter from "./CurrencyConverter"; 2 | 3 | class Cost { 4 | @CurrencyConverter("INR", "USD") 5 | compute(qty, price) { 6 | return Promise.resolve(qty * price); 7 | } 8 | } 9 | 10 | const price = new Cost(); 11 | price.compute(20, 5).then(result => console.log(result)); -------------------------------------------------------------------------------- /Section 5/code_5.1/Bank.js: -------------------------------------------------------------------------------- 1 | // Strategy 2 | class Bank { 3 | constructor(amount, account) { 4 | this.amount = amount; 5 | this.account = account; 6 | } 7 | pay() { 8 | return this.processPayment(); 9 | } 10 | refund() { 11 | return this.processRefund(); 12 | } 13 | } 14 | 15 | module.exports = Bank; 16 | -------------------------------------------------------------------------------- /Section 1/code_1.2/Singleton_Object/App.js: -------------------------------------------------------------------------------- 1 | const Till = require('./CashRegister'); 2 | const Till1 = require('./CashRegister'); 3 | 4 | Till.credit(25); 5 | Till.credit(35); 6 | 7 | Till1.credit(20); 8 | console.log(`Total amount in Till 1 : ${Till1.total()}`); 9 | 10 | Till.debit(5); 11 | console.log(`Total amount in Till : ${Till.total()}`); -------------------------------------------------------------------------------- /Section 4/code_4.3/Function/app.js: -------------------------------------------------------------------------------- 1 | const CurrencyConverter = require("./CurrencyConverter"); 2 | 3 | const Cost = (qty, price) => Promise.resolve(qty * price); 4 | Cost(20, 5).then(result => console.log(result)); 5 | 6 | // With Converter 7 | const CostPlus = CurrencyConverter(Cost); 8 | CostPlus(20, 5, "INR", "EUR").then(result => console.log(result)); -------------------------------------------------------------------------------- /Section 4/code_4.1/Vault/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "proxy-demo", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "cryptr": "^4.0.2" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Section 5/code_5.1/app.js: -------------------------------------------------------------------------------- 1 | const Payment = require("./Payment"); 2 | const Chase = require("./Chase"); 3 | const Citibank = require("./Citibank"); 4 | 5 | const payment = new Payment(); 6 | 7 | payment.pay(new Chase(200, "002340112450")); 8 | payment.pay(new Citibank(150, "00120198765")); 9 | 10 | payment.refund(new Chase(50, "002340112450")); 11 | -------------------------------------------------------------------------------- /Section 1/code_1.4/signup/App.js: -------------------------------------------------------------------------------- 1 | const SignupBuilder = require('./SignupBuilder'); 2 | 3 | // Signup.create('John Doe', 'john@email.com', 25, 'johndoe.jpg', 'John_D', ['JavaScript','Node.js'], ['Node.js'], true, false); 4 | 5 | new SignupBuilder('John Doe', 'john@email.com', 25) 6 | .setPhoto('johndoe.jpg') 7 | .setNick('John_D') 8 | .setAdmin() 9 | .create(); -------------------------------------------------------------------------------- /Section 5/code_5.3/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "colors": "^1.3.3" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Section 4/code_4.2/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "code", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "Db.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "lokijs": "^1.5.6", 13 | "lowdb": "^1.0.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Section 6/Code 6.2/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "amqplib": "^0.5.3" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Section 1/code_1.2/Singleton_Class/Game.js: -------------------------------------------------------------------------------- 1 | const Scores = require('./Scoreboard'); 2 | // const Scores = new ScoreBoard(); 3 | 4 | class Game { 5 | join(player) { 6 | Scores.join(player.getName()); 7 | } 8 | scores() { 9 | return Scores.getBoard(); 10 | } 11 | getWinner() { 12 | return Scores.sort()[0]; 13 | } 14 | } 15 | 16 | module.exports = Game; -------------------------------------------------------------------------------- /Section 1/code_1.3/app.js: -------------------------------------------------------------------------------- 1 | const iPhoneFactory = require('./iPhoneFactory'); 2 | 3 | const iPhoneXR = iPhoneFactory.create('iPhone Xr', 'xr-0001'); 4 | const iPhoneXS = iPhoneFactory.create('iPhone Xs', 'xs-0002'); 5 | const iPhoneXSMax = iPhoneFactory.create('iPhone Xs Max', 'xsmax-0003'); 6 | 7 | iPhoneXR.displayConfig(); 8 | iPhoneXS.displayConfig(); 9 | iPhoneXSMax.displayConfig(); -------------------------------------------------------------------------------- /Section 4/code_4.3/Function/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Function", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "axios": "^0.18.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Section 4/code_4.4/Laptop.js: -------------------------------------------------------------------------------- 1 | const Item = require("./Item"); 2 | 3 | class Laptop extends Item { 4 | constructor(name, model, cost) { 5 | super(name, "Laptop"); 6 | this.model = model; 7 | this.cost = cost; 8 | } 9 | getDetails() { 10 | console.log(`${this.getName()} ${this.model}, priced at INR ${this.cost}`); 11 | } 12 | } 13 | 14 | module.exports = Laptop; -------------------------------------------------------------------------------- /Section 6/code_6.1/app.js: -------------------------------------------------------------------------------- 1 | const wsUri = "ws://localhost:3000"; 2 | const wsServerPort = 3000; 3 | new (require("./Server"))(wsServerPort); 4 | 5 | const client = new (require("./Client"))(wsUri); 6 | 7 | client.send("This is my first message", res => console.log(`Task 1: ${res}`)); 8 | client.send("Hello Node.js, I'm a server!", res => 9 | console.log(`Task 2: ${res}`) 10 | ); 11 | -------------------------------------------------------------------------------- /Section 6/code_6.1/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "uuid": "^3.3.2", 14 | "ws": "^6.1.4" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Section 5/code_5.2/Invoker.js: -------------------------------------------------------------------------------- 1 | class Invoker { 2 | constructor(db) { 3 | this.stack = []; 4 | this.db = db; 5 | } 6 | execute(command) { 7 | this.stack.push(command); 8 | command.execute(this.db); 9 | } 10 | undo() { 11 | const lastCommand = this.stack.pop(); 12 | if (lastCommand) lastCommand.undo(this.db); 13 | } 14 | } 15 | 16 | module.exports = Invoker; 17 | -------------------------------------------------------------------------------- /Section 1/code_1.4/pizza/Pizza.js: -------------------------------------------------------------------------------- 1 | function Pizza() { 2 | this.pizza = {} 3 | this.setBase = base => this.pizza.base = base; 4 | this.setSauce = sauce => this.pizza.sauce = sauce; 5 | this.setCheese = cheese => this.pizza.cheese = cheese; 6 | this.setToppings = toppings => this.pizza.toppings = toppings; 7 | this.bake = () => console.log(this.pizza); 8 | } 9 | 10 | module.exports = Pizza; -------------------------------------------------------------------------------- /Section 5/code_5.2/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "command-pattern", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "colors": "^1.3.3", 14 | "lokijs": "^1.5.6" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Section 4/code_4.4/MobilePhone.js: -------------------------------------------------------------------------------- 1 | const Item = require("./Item"); 2 | 3 | class MobilePhone extends Item { 4 | constructor(name, color, cost) { 5 | super(name, "Mobile Phone"); 6 | this.color = color; 7 | this.cost = cost; 8 | } 9 | getDetails() { 10 | console.log(`${this.getName()} :: ${this.color} color, priced at INR ${this.cost}`); 11 | } 12 | } 13 | 14 | module.exports = MobilePhone; -------------------------------------------------------------------------------- /Section 1/code_1.2/Singleton_Class/Player.js: -------------------------------------------------------------------------------- 1 | const Scores = require('./Scoreboard'); 2 | // const Scores = new ScoreBoard(); 3 | 4 | class Player { 5 | constructor(name) { 6 | this.name = name; 7 | } 8 | getName() { 9 | return this.name; 10 | } 11 | wins(points) { 12 | Scores.update(this.name, points); 13 | } 14 | loses(points) { 15 | Scores.update(this.name, -points); 16 | } 17 | } 18 | 19 | module.exports = Player; -------------------------------------------------------------------------------- /Section 4/code_4.2/Db.js: -------------------------------------------------------------------------------- 1 | class Db { 2 | constructor(db) { 3 | this.db = db; 4 | } 5 | init(collection) { 6 | return this.db.defaults({ [collection]: [] }).write(); 7 | } 8 | add({ collection, data }) { 9 | return this.db 10 | .get(collection) 11 | .push(data) 12 | .write(); 13 | } 14 | get(collection) { 15 | return this.db.get(collection).value(); 16 | } 17 | } 18 | 19 | module.exports = Db; 20 | -------------------------------------------------------------------------------- /Section 4/code_4.4/Catalog.js: -------------------------------------------------------------------------------- 1 | const Item = require("./Item"); 2 | 3 | class Catalog extends Item { 4 | constructor(name) { 5 | super(name, "Catalog"); 6 | this.collection = []; 7 | } 8 | add(product) { 9 | this.collection.push(product); 10 | return this; 11 | } 12 | getDetails() { 13 | console.log(this.getName().toUpperCase()); 14 | this.collection.forEach(item => item.getDetails()); 15 | } 16 | } 17 | 18 | module.exports = Catalog; -------------------------------------------------------------------------------- /Section 1/code_1.2/Singleton_Object/CashRegister.js: -------------------------------------------------------------------------------- 1 | let cash = 0; // This is a private variable 2 | 3 | const CashRegister = { 4 | credit(amount) { 5 | cash = cash + amount; 6 | return cash; 7 | }, 8 | debit(amount) { 9 | if (amount <= cash) { 10 | cash = cash - amount; 11 | return true; 12 | } else { 13 | return false; 14 | } 15 | }, 16 | total() { 17 | return cash; 18 | } 19 | } 20 | 21 | module.exports = CashRegister; -------------------------------------------------------------------------------- /Section 4/code_4.1/Vault/app.js: -------------------------------------------------------------------------------- 1 | const { 2 | lock, 3 | unlock 4 | } = require("./Vault"); 5 | const password = "thisisastrongpassword123"; 6 | 7 | const obj = { 8 | name: "John Doe", 9 | age: 32, 10 | city: "Chicago", 11 | country: "US" 12 | }; 13 | 14 | const person = lock(obj, password); 15 | person.favColor = "Red"; 16 | person.favFruit = "Apple"; 17 | console.log(person); 18 | 19 | const unlocked = unlock(person, password); 20 | // unlocked.food = "Pizza"; 21 | console.log(unlocked); -------------------------------------------------------------------------------- /Section 3/code_3.2/file-logger/index.js: -------------------------------------------------------------------------------- 1 | const { 2 | appendFile 3 | } = require("fs"); 4 | const { 5 | join 6 | } = require("path"); 7 | const logFile = join(__dirname, "activity.log"); 8 | 9 | const write = (log = null) => { 10 | if (log) { 11 | appendFile(logFile, `${new Date()} : ${log}\n`, error => { 12 | if (error) { 13 | return console.log("There was an error writing to the log file!"); 14 | } 15 | }); 16 | } 17 | } 18 | 19 | module.exports = { 20 | write 21 | } -------------------------------------------------------------------------------- /Section 5/code_5.1/Chase.js: -------------------------------------------------------------------------------- 1 | const Bank = require("./Bank"); 2 | 3 | class Chase extends Bank { 4 | processPayment() { 5 | console.log( 6 | `Your payment of ${this.amount} for ${ 7 | this.account 8 | } has been processed by Chase` 9 | ); 10 | } 11 | processRefund() { 12 | console.log( 13 | `A refund of amount ${this.amount} for ${ 14 | this.account 15 | } has been processed by Chase` 16 | ); 17 | } 18 | } 19 | 20 | module.exports = Chase; 21 | -------------------------------------------------------------------------------- /Section 5/code_5.3/Store.js: -------------------------------------------------------------------------------- 1 | const events = require("./EventBus"); 2 | const colors = require("colors"); 3 | 4 | class Store { 5 | constructor() { 6 | events.on("new-post", data => this.writeToDb(data)); 7 | } 8 | writeToDb({topic, message}) { 9 | console.log( 10 | colors.red( 11 | `STORE ::: Storing "${colors.yellow( 12 | message 13 | )}" under TOPIC :: ${topic.toUpperCase()}` 14 | ) 15 | ); 16 | } 17 | } 18 | 19 | module.exports = new Store(); 20 | -------------------------------------------------------------------------------- /Section 4/code_4.1/Reactive/Reactive.js: -------------------------------------------------------------------------------- 1 | const obj = { 2 | name: "John Doe", 3 | age: 32, 4 | city: "Chicago", 5 | country: "US" 6 | }; 7 | 8 | const makeReactive = (obj, observer) => { 9 | return new Proxy(obj, { 10 | set(target, key, value) { 11 | observer({ 12 | [key]: value 13 | }); 14 | return (target[key] = value); 15 | } 16 | }); 17 | } 18 | 19 | const reactive = makeReactive(obj, res => console.log(res)); 20 | reactive.color = "Green"; 21 | reactive.age = 33; -------------------------------------------------------------------------------- /Section 5/code_5.3/app.js: -------------------------------------------------------------------------------- 1 | const Topic = require("./Topic"); 2 | const User = require("./User"); 3 | const Store = require("./Store"); 4 | 5 | const John = new User("John Doe"); 6 | const Mike = new User("Michael Williams"); 7 | 8 | const NodeJS = new Topic("Node.js"); 9 | const ReactJS = new Topic("React.js"); 10 | 11 | NodeJS.subscribe(John); 12 | NodeJS.subscribe(Mike); 13 | ReactJS.subscribe(Mike); 14 | 15 | NodeJS.add("A brand new version of Node.js is out!!"); 16 | ReactJS.add("React introduces Hooks"); 17 | -------------------------------------------------------------------------------- /Section 5/code_5.1/Citibank.js: -------------------------------------------------------------------------------- 1 | const Bank = require("./Bank"); 2 | 3 | class Citibank extends Bank { 4 | processPayment() { 5 | console.log( 6 | `Your payment of ${this.amount} for ${ 7 | this.account 8 | } has been processed by Citibank` 9 | ); 10 | } 11 | processRefund() { 12 | console.log( 13 | `A refund of amount ${this.amount} for ${ 14 | this.account 15 | } has been processed by Citibank` 16 | ); 17 | } 18 | } 19 | 20 | module.exports = Citibank; 21 | -------------------------------------------------------------------------------- /Section 1/code_1.4/signup/Signup.js: -------------------------------------------------------------------------------- 1 | const User = require('./User'); 2 | const UserPref = require('./UserPref'); 3 | 4 | class Signup { 5 | async create({ 6 | name, 7 | email, 8 | age, 9 | photo, 10 | nickname, 11 | favoriteTopics, 12 | isSME, 13 | isModerator, 14 | isAdmin 15 | }) { 16 | const newUser = await new User(name, email, age, photo); 17 | await new UserPref(newUser, nickname, favoriteTopics, isSME, isModerator, isAdmin); 18 | } 19 | } 20 | 21 | module.exports = new Signup(); -------------------------------------------------------------------------------- /Section 5/code_5.2/app.js: -------------------------------------------------------------------------------- 1 | const Invoker = require("./Invoker"); 2 | const Db = require("./Database"); 3 | const Post = require("./Post"); 4 | const Update = require("./Update"); 5 | const View = require("./View"); 6 | 7 | const Blog = new Invoker(Db); 8 | 9 | Blog.execute( 10 | new Post("My First Post", "Hello everyone, this is my first post!") 11 | ); 12 | Blog.execute( 13 | new Post( 14 | "About Design Patterns", 15 | "So, I'm building a course on design patterns for Node.js" 16 | ) 17 | ); 18 | Blog.execute(new View()); 19 | -------------------------------------------------------------------------------- /Section 5/code_5.2/View.js: -------------------------------------------------------------------------------- 1 | const Command = require("./Command"); 2 | const colors = require("colors"); 3 | 4 | class View extends Command { 5 | constructor(query = {}) { 6 | super(); 7 | this.query = query; 8 | } 9 | execute(db) { 10 | const results = db.getPost(this.query); 11 | results.forEach(item => 12 | console.log( 13 | `${colors.green(item.title)} [${colors.red(item.timestamp)}]: ${ 14 | item.content 15 | }` 16 | ) 17 | ); 18 | } 19 | } 20 | 21 | module.exports = View; 22 | -------------------------------------------------------------------------------- /Section 5/code_5.2/Post.js: -------------------------------------------------------------------------------- 1 | const Command = require("./Command"); 2 | 3 | class Post extends Command { 4 | constructor(title, content) { 5 | super(); 6 | this.title = title; 7 | this.content = content; 8 | this.id = new Date().getTime(); 9 | } 10 | execute(db) { 11 | db.push({ 12 | title: this.title, 13 | content: this.content, 14 | timestamp: new Date().toISOString(), 15 | id: this.id 16 | }); 17 | } 18 | undo(db) { 19 | db.remove(this.id); 20 | } 21 | } 22 | 23 | module.exports = Post; 24 | -------------------------------------------------------------------------------- /Section 4/code_4.3/Function/CurrencyConverter.js: -------------------------------------------------------------------------------- 1 | const axios = require("axios"); 2 | 3 | const CurrencyConverter = fn => { 4 | return async function (qty, price, base, to) { 5 | const result = await fn(qty, price); // Call the original function 6 | const currencyRate = await axios(`https://free.currencyconverterapi.com/api/v6/convert?q=${to.toUpperCase()}_${base.toUpperCase()}&compact=y`); 7 | 8 | return (currencyRate.data[`${to.toUpperCase()}_${base.toUpperCase()}`]["val"] * result); 9 | } 10 | } 11 | 12 | module.exports = CurrencyConverter; -------------------------------------------------------------------------------- /Section 2/code_2.4/fruit-salad/fruitSalad.js: -------------------------------------------------------------------------------- 1 | const fruits = ["Apples", "Oranges", "Kiwi", "Strawberries"]; 2 | 3 | function* fruitShop() { 4 | for (const fruit of fruits) { 5 | yield fruit; 6 | } 7 | } 8 | 9 | const getFruits = fruitShop(); 10 | 11 | function makeSalad() { 12 | let fruitBasket = getFruits.next(); 13 | if (!fruitBasket.done) { 14 | console.log(fruitBasket.value); // Do something with the value from the array 15 | makeSalad(); 16 | } else { 17 | console.log("--- We're out of fruits! ---"); 18 | } 19 | } 20 | 21 | makeSalad(); -------------------------------------------------------------------------------- /Section 5/code_5.4/app.js: -------------------------------------------------------------------------------- 1 | const Middleware = require("./Middleware"); 2 | 3 | class Maths { 4 | add({a, b}) { 5 | return a + b; 6 | } 7 | subtract({a, b}) { 8 | return a - b; 9 | } 10 | multiply({a, b}) { 11 | return a * b; 12 | } 13 | } 14 | 15 | const calculator = new Maths(); 16 | const app = new Middleware(calculator); 17 | 18 | app.use((req, next) => { 19 | req.a = req.a * 2; 20 | next(); 21 | }); 22 | 23 | app.use((req, next) => { 24 | req.b = req.b * 3; 25 | next(); 26 | }); 27 | 28 | console.log(app.add({a: 5, b: 10})); 29 | -------------------------------------------------------------------------------- /Section 1/code_1.2/Singleton_Class/App.js: -------------------------------------------------------------------------------- 1 | const Game = require('./Game'); 2 | const Player = require('./Player'); 3 | 4 | const Pete = new Player('Pete'); 5 | const Mike = new Player('Mike'); 6 | const Poker = new Game(); 7 | 8 | Poker.join(Pete); 9 | Poker.join(Mike); 10 | 11 | Pete.wins(20); 12 | 13 | Mike.wins(30); 14 | Mike.wins(40); 15 | Mike.wins(40); 16 | Mike.wins(40); 17 | 18 | Pete.wins(1000); 19 | Pete.loses(1000); 20 | 21 | console.log('Scoreboard: ', Poker.scores()); 22 | console.log(`Winner: ${Poker.getWinner().name} with ${Poker.getWinner().points} points`); -------------------------------------------------------------------------------- /Section 5/code_5.3/Topic.js: -------------------------------------------------------------------------------- 1 | const emitter = require("./EventBus"); 2 | 3 | class Topic { 4 | constructor(topic) { 5 | this.topic = topic; 6 | this.subscribers = []; 7 | this.posts = []; 8 | } 9 | subscribe(user) { 10 | this.subscribers.push(user.getName); 11 | } 12 | add(msg) { 13 | this.posts.push(msg); 14 | this.notify(msg); 15 | } 16 | notify(message) { 17 | emitter.emit("new-post", { 18 | topic: this.topic, 19 | message, 20 | subscribers: this.subscribers 21 | }); 22 | } 23 | } 24 | 25 | module.exports = Topic; 26 | -------------------------------------------------------------------------------- /Section 3/code_3.2/app.js: -------------------------------------------------------------------------------- 1 | const Bank = require("./Bank"); 2 | // const logger = require("./console-logger"); 3 | const logger = require("./file-logger"); 4 | const user1 = "John Doe"; 5 | const user2 = "Richard Helm"; 6 | 7 | Bank.config({ 8 | logger 9 | }); 10 | 11 | Bank.createAccount(user1); 12 | Bank.credit(user1, 20); 13 | Bank.credit(user1, 50); 14 | Bank.credit(user1, 120); 15 | Bank.debit(user1, 10); 16 | console.log(user2, Bank.getFunds(user1)); 17 | 18 | Bank.createAccount(user2); 19 | Bank.credit(user2, 200); 20 | Bank.debit(user2, 25); 21 | console.log(user2, Bank.getFunds(user2)); -------------------------------------------------------------------------------- /Section 5/code_5.3/User.js: -------------------------------------------------------------------------------- 1 | const events = require("./EventBus"); 2 | const colors = require("colors"); 3 | 4 | class User { 5 | constructor(name) { 6 | this.name = name; 7 | events.on("new-post", ({topic, subscribers}) => 8 | subscribers.includes(this.name) ? this.notify(topic) : null 9 | ); 10 | } 11 | get getName() { 12 | return this.name; 13 | } 14 | notify(topic) { 15 | console.log( 16 | colors.green( 17 | `NOTIFICATION ::: ${ 18 | this.name 19 | }, a new message has been posted under ${topic}` 20 | ) 21 | ); 22 | } 23 | } 24 | 25 | module.exports = User; 26 | -------------------------------------------------------------------------------- /Section 1/code_1.3/iPhoneFactory.js: -------------------------------------------------------------------------------- 1 | const iPhoneXR = require('./iPhoneXR'); 2 | const iPhoneXS = require('./iPhoneXS'); 3 | const iPhoneXSMax = require('./iPhoneXSMax'); 4 | 5 | class iPhoneFactory { 6 | create(type, serialNum) { 7 | switch (type) { 8 | case 'iPhone Xr': 9 | return new iPhoneXR(serialNum); 10 | case 'iPhone Xs': 11 | return new iPhoneXS(serialNum); 12 | case 'iPhone Xs Max': 13 | return new iPhoneXSMax(serialNum); 14 | default: 15 | { 16 | console.log('Unknown iPhone type...'); 17 | } 18 | } 19 | } 20 | } 21 | 22 | module.exports = new iPhoneFactory(); -------------------------------------------------------------------------------- /Section 4/code_4.3/Class/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "class", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "dev": "parcel --target=node app.js", 8 | "build": "parcel build --target=node app.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.2.2", 14 | "@babel/plugin-proposal-decorators": "^7.3.0", 15 | "@babel/plugin-transform-runtime": "^7.2.0", 16 | "parcel-bundler": "^1.11.0" 17 | }, 18 | "engines": { 19 | "node": ">=8.0.0" 20 | }, 21 | "dependencies": { 22 | "axios": "^0.18.0" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Section 1/code_1.3/Phone.js: -------------------------------------------------------------------------------- 1 | class Phone { 2 | constructor( 3 | serialNum, 4 | model = 'Generic', 5 | processor = 'Generic', 6 | RAM = '2 Gb', 7 | width = 67.3, 8 | height = 138.4, 9 | depth = 7.3, 10 | resolution = '750 x 1334' 11 | ) { 12 | this.serialNum = serialNum; 13 | this.configuration = { 14 | model, 15 | processor, 16 | RAM, 17 | width, 18 | height, 19 | depth, 20 | resolution 21 | } 22 | } 23 | dial(num) { 24 | console.log(`Now dialing ${num}...`); 25 | } 26 | displayConfig() { 27 | console.log(this.configuration); 28 | } 29 | } 30 | 31 | module.exports = Phone; -------------------------------------------------------------------------------- /Section 6/Code 6.2/Subscriber.js: -------------------------------------------------------------------------------- 1 | const Rabbit = require("./Rabbit"); 2 | const exchange = "announcements"; 3 | 4 | const RabbitHears = async () => { 5 | try { 6 | const conn = await Rabbit(); 7 | const channel = await conn.createChannel(); 8 | const qok = await channel.assertQueue("", {exclusive: true}); 9 | const bindQueue = await channel.bindQueue(qok.queue, exchange, ""); 10 | await channel.consume( 11 | bindQueue.queue, 12 | msg => console.log(`>:> ${msg.content.toString()}`), 13 | {noAck: true} 14 | ); 15 | } catch ({code}) { 16 | console.log(code === "ECONNREFUSED" ? "RabbitMQ is offline" : code); 17 | } 18 | }; 19 | 20 | RabbitHears(); 21 | -------------------------------------------------------------------------------- /Section 1/code_1.2/Singleton_Class/Scoreboard.js: -------------------------------------------------------------------------------- 1 | class Scoreboard { 2 | constructor() { 3 | this.board = []; 4 | } 5 | join(name) { 6 | this.board.push({ 7 | name, 8 | points: 0 9 | }); 10 | } 11 | leave(name) { 12 | this.board = this.board.filter(player => player.name !== name); 13 | } 14 | update(name, points) { 15 | const player = this.board.findIndex(player => player.name === name); 16 | if (player > -1) { 17 | this.board[player].points += points; 18 | } 19 | } 20 | getBoard() { 21 | return this.board; 22 | } 23 | sort() { 24 | return this.board.sort((x, y) => y.points - x.points); 25 | } 26 | } 27 | 28 | module.exports = new Scoreboard(); -------------------------------------------------------------------------------- /Section 1/code_1.4/signup/User.js: -------------------------------------------------------------------------------- 1 | const { 2 | randomBytes 3 | } = require('crypto'); 4 | 5 | class User { 6 | constructor(name, email, age, photo) { 7 | return new Promise((resolve, reject) => { 8 | this.name = name; 9 | this.email = email; 10 | this.age = age; 11 | this.photo = photo; 12 | resolve(this._doSignup()); 13 | }); 14 | } 15 | _setPhoto() { 16 | console.log(`- New photo ${this.photo} uploaded for ${this.name}`); 17 | } 18 | _doSignup() { 19 | if (this.photo) { 20 | this._setPhoto(); 21 | } 22 | console.log(`- ${this.name} signed up as a new user!`); 23 | return randomBytes(12).toString('hex'); 24 | } 25 | } 26 | 27 | module.exports = User; -------------------------------------------------------------------------------- /Section 5/code_5.2/Update.js: -------------------------------------------------------------------------------- 1 | const Command = require("./Command"); 2 | 3 | class Update extends Command { 4 | constructor(title, content) { 5 | super(); 6 | this.title = title; 7 | this.content = content; 8 | this.oldPost = ""; 9 | } 10 | execute(db) { 11 | const getOld = db.getPost({ title: this.title }); 12 | if (getOld.length === 0) { 13 | console.log("UPDATE FAILED: Post not found!"); 14 | } else { 15 | this.oldPost = getOld[0].content; 16 | this.update(db); 17 | } 18 | } 19 | update(db) { 20 | db.update(this.title, this.content); 21 | } 22 | undo(db) { 23 | db.update(this.title, this.oldPost); 24 | } 25 | } 26 | 27 | module.exports = Update; 28 | -------------------------------------------------------------------------------- /Section 3/code_3.2/file-logger/activity.log: -------------------------------------------------------------------------------- 1 | Sat Jan 19 2019 22:48:57 GMT+0530 (India Standard Time) : Account created for XXXXXXXXNDOE 2 | Sat Jan 19 2019 22:48:57 GMT+0530 (India Standard Time) : 20 credited to XXXXXXXXNDOE 3 | Sat Jan 19 2019 22:48:57 GMT+0530 (India Standard Time) : 120 credited to XXXXXXXXNDOE 4 | Sat Jan 19 2019 22:48:57 GMT+0530 (India Standard Time) : 50 credited to XXXXXXXXNDOE 5 | Sat Jan 19 2019 22:48:57 GMT+0530 (India Standard Time) : 10 debited from XXXXXXXXNDOE 6 | Sat Jan 19 2019 22:48:57 GMT+0530 (India Standard Time) : Account created for XXXXXXXXHELM 7 | Sat Jan 19 2019 22:48:57 GMT+0530 (India Standard Time) : 200 credited to XXXXXXXXHELM 8 | Sat Jan 19 2019 22:48:57 GMT+0530 (India Standard Time) : 25 debited from XXXXXXXXHELM 9 | -------------------------------------------------------------------------------- /Section 5/code_5.5/Chase.js: -------------------------------------------------------------------------------- 1 | const Bank = require("./Bank"); 2 | 3 | class Chase extends Bank { 4 | constructor() { 5 | super(); 6 | } 7 | processCredit(name, amount) { 8 | const getAccount = this._getAccount(name); 9 | if (getAccount) { 10 | getAccount.funds = getAccount.funds + amount; 11 | } else { 12 | console.log("Account not found!"); 13 | } 14 | } 15 | processDebit(name, amount) { 16 | const getAccount = this._getAccount(name); 17 | if (getAccount) { 18 | const debitAmount = getAccount.funds - amount; 19 | getAccount.funds = debitAmount <= 0 ? getAccount.funds : debitAmount; 20 | } else { 21 | console.log("Account not found!"); 22 | } 23 | } 24 | } 25 | 26 | module.exports = Chase; 27 | -------------------------------------------------------------------------------- /Section 4/code_4.2/app.js: -------------------------------------------------------------------------------- 1 | const Db = require("./Db"); 2 | const { 3 | join 4 | } = require("path"); 5 | 6 | // Database File 7 | const dbFile = join("dbs.json"); 8 | 9 | // LowDB 10 | // const low = require("lowdb"); 11 | // const FileSync = require("lowdb/adapters/FileSync"); 12 | // const adapter = new FileSync(dbFile); 13 | // const dbs = low(adapter); 14 | 15 | // LokiJS 16 | const loki = require("lokijs"); 17 | const LokiAdapter = require("./LokiAdapter"); 18 | const ldb = new loki(dbFile); 19 | const LokiAdp = new LokiAdapter(ldb); 20 | 21 | 22 | // DB module instance 23 | const db = new Db(LokiAdp); 24 | 25 | db.init("users"); 26 | db.add({ 27 | collection: "users", 28 | data: { 29 | name: "John Doe", 30 | age: 32 31 | } 32 | }); 33 | 34 | console.log(db.get("users")); -------------------------------------------------------------------------------- /Section 4/code_4.3/Class/CurrencyConverter.js: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | 3 | const CurrencyConverter = (base, to) => { 4 | return function (target, name, descriptor) { 5 | try { 6 | const fn = descriptor.value; // The original function 7 | descriptor.value = async (...args) => { 8 | // Define the decorator 9 | const result = await fn.call(this, ...args); 10 | const currencyRate = await axios(`https://free.currencyconverterapi.com/api/v6/convert?q=${to.toUpperCase()}_${base.toUpperCase()}&compact=y`); 11 | 12 | return await (currencyRate.data[`${to.toUpperCase()}_${base.toUpperCase()}`]["val"] * result); 13 | } 14 | 15 | return descriptor; 16 | } catch (error) { 17 | console.log(error); 18 | } 19 | } 20 | } 21 | 22 | export default CurrencyConverter; -------------------------------------------------------------------------------- /Section 5/code_5.2/Database.js: -------------------------------------------------------------------------------- 1 | const { join } = require("path"); 2 | const loki = require("lokijs"); 3 | const dbs = new loki(join(__dirname, "dbs.json")); 4 | dbs.addCollection("posts"); 5 | 6 | class Database { 7 | constructor(db) { 8 | this.db = db; 9 | } 10 | getPost(obj = {}) { 11 | return this.db.getCollection("posts").find(obj); 12 | } 13 | push(obj) { 14 | this.db.getCollection("posts").insert(obj); 15 | this.db.saveDatabase(); 16 | } 17 | remove(id) { 18 | this.db.getCollection("posts").findAndRemove({ id }); 19 | this.db.saveDatabase(); 20 | } 21 | update(title, content) { 22 | this.db 23 | .getCollection("posts") 24 | .findAndUpdate({ title }, obj => (obj.content = content)); 25 | this.db.saveDatabase(); 26 | } 27 | } 28 | 29 | module.exports = new Database(dbs); 30 | -------------------------------------------------------------------------------- /Section 6/code_6.1/Server.js: -------------------------------------------------------------------------------- 1 | const SocketServer = require("ws").Server; 2 | const reverse = str => 3 | str 4 | .split("") 5 | .reverse() 6 | .join(""); 7 | 8 | class Server { 9 | constructor(port) { 10 | this.server = new SocketServer({port}); 11 | this.server.on("connection", ws => this.connectionHandler.call(this, ws)); 12 | } 13 | connectionHandler(ws) { 14 | ws.on("message", msg => { 15 | const {textToProcess, correlationId, key} = JSON.parse(msg); 16 | if (key === "request" && textToProcess) { 17 | const reply = reverse(textToProcess); 18 | const payload = JSON.stringify({ 19 | key: "reply", 20 | correlationId, 21 | reply 22 | }); 23 | ws.send(payload); 24 | } 25 | }); 26 | } 27 | } 28 | 29 | module.exports = Server; 30 | -------------------------------------------------------------------------------- /Section 1/code_1.4/signup/SignupBuilder.js: -------------------------------------------------------------------------------- 1 | const Signup = require('./Signup'); 2 | 3 | class SignupBuilder { 4 | constructor(name, email, age) { 5 | this.name = name; 6 | this.email = email; 7 | this.age = age; 8 | } 9 | setNick(name) { 10 | this.nickname = name; 11 | return this; 12 | } 13 | setPhoto(photo) { 14 | this.photo = photo; 15 | return this; 16 | } 17 | setTopics(topics) { 18 | this.favoriteTopics = topics; 19 | return this; 20 | } 21 | setSME(topics) { 22 | this.isSME = topics; 23 | return this; 24 | } 25 | setModerator() { 26 | this.isModerator = true; 27 | return this; 28 | } 29 | setAdmin() { 30 | this.isAdmin = true; 31 | return this; 32 | } 33 | create() { 34 | return Signup.create(this); 35 | } 36 | } 37 | 38 | module.exports = SignupBuilder; -------------------------------------------------------------------------------- /Section 5/code_5.4/Middleware.js: -------------------------------------------------------------------------------- 1 | class Middleware { 2 | constructor(target) { 3 | this.target = target; 4 | this.middlewares = []; 5 | this.req = {}; 6 | 7 | const prototype = Object.getPrototypeOf(this.target); 8 | Object.getOwnPropertyNames(prototype).forEach(fn => { 9 | if (fn !== "constructor") return this.createFn(fn); 10 | }); 11 | } 12 | use(middleware) { 13 | this.middlewares.push(middleware); 14 | } 15 | executeMiddleware(i = 0) { 16 | if (i < this.middlewares.length) { 17 | this.middlewares[i].call(this, this.req, () => 18 | this.executeMiddleware(i + 1) 19 | ); 20 | } 21 | } 22 | createFn(fn) { 23 | this[fn] = args => { 24 | this.req = args; 25 | this.executeMiddleware(); 26 | return this.target[fn].call(this, this.req); 27 | }; 28 | } 29 | } 30 | 31 | module.exports = Middleware; 32 | -------------------------------------------------------------------------------- /Section 4/code_4.1/Vault/Vault.js: -------------------------------------------------------------------------------- 1 | const Cryptr = require("cryptr"); 2 | 3 | const lock = (obj, password) => { 4 | const cryptr = new Cryptr(password); 5 | let newObj = {}; 6 | for (const i of Object.keys(obj)) { 7 | newObj[i] = cryptr.encrypt(obj[i]); 8 | } 9 | 10 | return new Proxy(newObj, { 11 | set(target, key, value) { 12 | return (target[key] = cryptr.encrypt(value)); 13 | }, 14 | get(target, key) { 15 | return target[key]; 16 | } 17 | }); 18 | } 19 | 20 | const unlock = (obj, password) => { 21 | const cryptr = new Cryptr(password); 22 | let newObj = {}; 23 | for (const i of Object.keys(obj)) { 24 | newObj[i] = cryptr.decrypt(obj[i]); 25 | } 26 | 27 | return new Proxy(newObj, { 28 | set() { 29 | throw new Error("This is a read-only object"); 30 | } 31 | }); 32 | } 33 | 34 | module.exports = { 35 | lock, 36 | unlock 37 | } -------------------------------------------------------------------------------- /Section 3/code_3.1/classes/Bank.js: -------------------------------------------------------------------------------- 1 | let accounts = []; 2 | const findAccount = Symbol("findAccount"); 3 | 4 | class Bank { 5 | [findAccount](name) { 6 | return accounts.find(acc => acc.name === name); 7 | } 8 | createAccount(name, monies = 0) { 9 | if (!this[findAccount](name)) { 10 | accounts.push({ 11 | name, 12 | monies 13 | }); 14 | } else { 15 | console.log("An account already exists"); 16 | } 17 | } 18 | credit(name, amount) { 19 | if (this[findAccount](name)) { 20 | accounts.forEach(acc => { 21 | if (acc.name === name) { 22 | acc.monies = acc.monies + amount; 23 | } 24 | }); 25 | } 26 | } 27 | getFunds(name) { 28 | if (this[findAccount](name)) { 29 | return accounts.find(acc => acc.name === name)["monies"]; 30 | } 31 | return "Account not found!"; 32 | } 33 | } 34 | 35 | module.exports = new Bank(); -------------------------------------------------------------------------------- /Section 2/code_2.1/app.js: -------------------------------------------------------------------------------- 1 | const { 2 | readdir, 3 | readFile, 4 | writeFile 5 | } = require("fs"); 6 | const { 7 | join 8 | } = require("path"); 9 | const inbox = join(__dirname, "inbox"); 10 | const outbox = join(__dirname, "outbox"); 11 | 12 | const reverseText = str => 13 | str 14 | .split("") 15 | .reverse() 16 | .join(""); 17 | 18 | // Read and reverse contents of text files in a directory 19 | readdir(inbox, (error, files) => { 20 | if (error) return console.log("Error: Folder inaccessible"); 21 | files.forEach(file => { 22 | readFile(join(inbox, file), "utf8", (error, data) => { 23 | if (error) return console.log("Error: File error"); 24 | writeFile(join(outbox, file), reverseText(data), error => { 25 | if (error) return console.log("Error: File could not be saved!"); 26 | console.log(`${file} was successfully saved in the outbox!`); 27 | }); 28 | }); 29 | }); 30 | }); -------------------------------------------------------------------------------- /Section 5/code_5.5/Bank.js: -------------------------------------------------------------------------------- 1 | class Bank { 2 | constructor() { 3 | this.vault = []; 4 | } 5 | createAccount(name, initialDeposit) { 6 | this.vault.push({ 7 | name, 8 | funds: initialDeposit 9 | }); 10 | } 11 | _getAccount(name) { 12 | return this.vault.find(account => account.name === name); 13 | } 14 | view(name) { 15 | const getAccount = this._getAccount(name); 16 | if (getAccount) { 17 | console.log(`Account [${getAccount.name}] has USD ${getAccount.funds}`); 18 | } else { 19 | console.log("Account not found!"); 20 | } 21 | } 22 | credit(name, amount) { 23 | console.log(`Crediting ${amount} to account: ${name}`); 24 | return this.processCredit(name, amount); 25 | } 26 | debit(name, amount) { 27 | console.log(`Debiting ${amount} from account: ${name}`); 28 | return this.processDebit(name, amount); 29 | } 30 | } 31 | 32 | module.exports = Bank; 33 | -------------------------------------------------------------------------------- /Section 6/code_6.1/Client.js: -------------------------------------------------------------------------------- 1 | const Socket = require("ws"); 2 | const uuid = require("uuid/v4"); 3 | 4 | class Client { 5 | constructor(wsUri) { 6 | this.socket = new Socket(wsUri); 7 | this.socket.on("message", msg => 8 | this.receiveMessage.call(this, JSON.parse(msg)) 9 | ); 10 | this.handlers = {}; 11 | } 12 | receiveMessage({key, correlationId, reply}) { 13 | if (key === "reply" && typeof this.handlers[correlationId] === "function") { 14 | this.handlers[correlationId](reply); 15 | delete this.handlers[correlationId]; 16 | } 17 | } 18 | send(textToProcess, callback) { 19 | this.socket.on("open", () => { 20 | const correlationId = uuid(); 21 | this.handlers[correlationId] = callback; 22 | const payload = JSON.stringify({ 23 | key: "request", 24 | textToProcess, 25 | correlationId 26 | }); 27 | this.socket.send(payload); 28 | }); 29 | } 30 | } 31 | 32 | module.exports = Client; 33 | -------------------------------------------------------------------------------- /Section 6/Code 6.2/Publisher.js: -------------------------------------------------------------------------------- 1 | const Rabbit = require("./Rabbit"); 2 | const readLine = require("readline"); 3 | const exchange = "announcements"; 4 | 5 | const rl = readLine.createInterface({ 6 | input: process.stdin, 7 | output: process.stdout, 8 | terminal: false 9 | }); 10 | 11 | const RabbitSays = async message => { 12 | try { 13 | const conn = await Rabbit(); 14 | const channel = await conn.createChannel(); 15 | await channel.assertExchange(exchange, "fanout", {durable: false}); 16 | await channel.publish(exchange, "", Buffer.from(message)); 17 | await channel.close(); 18 | return conn.close(); 19 | } catch ({code}) { 20 | console.log(code === "ECONNREFUSED" ? "RabbitMQ is offline" : code); 21 | process.exit(0); 22 | } 23 | }; 24 | 25 | rl.setPrompt(":> "); 26 | rl.prompt(); 27 | rl.on("line", message => { 28 | if (message === "quit") { 29 | process.exit(0); 30 | } else { 31 | RabbitSays(message); 32 | rl.prompt(); 33 | } 34 | }); 35 | -------------------------------------------------------------------------------- /Section 4/code_4.4/app.js: -------------------------------------------------------------------------------- 1 | const MobilePhone = require("./MobilePhone"); 2 | const Laptop = require("./Laptop"); 3 | const Catalog = require("./Catalog"); 4 | 5 | // Phones 6 | const iPhoneXS = new MobilePhone("Apple iPhone XR", "White", 89000); 7 | const OnePlus6t = new MobilePhone("OnePlus 6T", "Midnight Black", 46000); 8 | const GalaxyM20 = new MobilePhone("Samsung Galaxy M20", "Ocean Blue", 12000); 9 | // Phone Catalog 10 | const Phones = new Catalog("** Mobile Phones **"); 11 | Phones.add(iPhoneXS).add(OnePlus6t).add(GalaxyM20); 12 | 13 | // Laptops 14 | const MacbookPro = new Laptop("Apple", "Macbook Pro 13", 150000); 15 | const DellInspiron = new Laptop("Dell", "Inspiron 5370", 63000); 16 | // Laptop Catalog 17 | const Laptops = new Catalog("** Laptops **"); 18 | Laptops.add(MacbookPro).add(DellInspiron); 19 | 20 | //Laptops.getDetails(); 21 | 22 | // Shopping Catalog 23 | const PrimeProducts = new Catalog("*** Prime Products 2019 ***"); 24 | PrimeProducts.add(Phones).add(Laptops); 25 | 26 | PrimeProducts.getDetails(); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Section 4/code_4.2/dbs.json: -------------------------------------------------------------------------------- 1 | {"filename":"dbs.json","collections":[{"name":"users","data":[{"name":"John Doe","age":32,"meta":{"revision":0,"created":1548673794954,"version":0},"$loki":1}],"idIndex":[1],"binaryIndices":{},"constraints":null,"uniqueNames":[],"transforms":{},"objType":"users","dirty":false,"cachedIndex":null,"cachedBinaryIndex":null,"cachedData":null,"adaptiveBinaryIndices":true,"transactional":false,"cloneObjects":false,"cloneMethod":"parse-stringify","asyncListeners":false,"disableMeta":false,"disableChangesApi":true,"disableDeltaChangesApi":true,"autoupdate":false,"serializableIndices":true,"ttl":null,"maxId":1,"DynamicViews":[],"events":{"insert":[],"update":[],"pre-insert":[],"pre-update":[],"close":[],"flushbuffer":[],"error":[],"delete":[null],"warning":[null]},"changes":[]}],"databaseVersion":1.5,"engineVersion":1.5,"autosave":false,"autosaveInterval":5000,"autosaveHandle":null,"throttledSaves":true,"options":{"serializationMethod":"normal","destructureDelimiter":"$<\n"},"persistenceMethod":"fs","persistenceAdapter":null,"verbose":false,"events":{"init":[null],"loaded":[],"flushChanges":[],"close":[],"changes":[],"warning":[]},"ENV":"NODEJS"} -------------------------------------------------------------------------------- /Section 2/code_2.2/app.js: -------------------------------------------------------------------------------- 1 | const { 2 | readdir, 3 | readFile, 4 | writeFile 5 | } = require("fs"); 6 | const { 7 | join 8 | } = require("path"); 9 | const { 10 | promisify 11 | } = require("util"); 12 | const inbox = join(__dirname, "inbox"); 13 | const outbox = join(__dirname, "outbox"); 14 | 15 | const reverseText = str => 16 | Promise.resolve(str 17 | .split("") 18 | .reverse() 19 | .join("")); 20 | 21 | const readdirAsync = promisify(readdir); // Promisified version of readdir 22 | const readFileAsync = promisify(readFile); 23 | const writeFileAsync = promisify(writeFile); 24 | 25 | // Read and reverse contents of text files in a directory 26 | const readReverseWrite = file => 27 | readFileAsync(join(inbox, file), "utf8") 28 | .then(reverseText) 29 | .then(data => writeFileAsync(join(outbox, file), data)) 30 | .then(() => console.log(`${file} has been processed!`)); 31 | 32 | readdirAsync(inbox) 33 | .then(files => files.map(file => readReverseWrite(file))) 34 | .then(promises => Promise.all(promises)) 35 | .then(() => console.log("*** All files processed ***")) 36 | .catch(error => console.log(`Error: ${error}`)); -------------------------------------------------------------------------------- /Section 3/code_3.1/modules/Bank.js: -------------------------------------------------------------------------------- 1 | let _accounts = []; 2 | 3 | const _findAccount = name => _accounts.find(acc => acc.name === name); 4 | 5 | const createAccount = (name, monies = 0) => { 6 | if (!_findAccount(name)) { 7 | _accounts.push({ 8 | name, 9 | monies 10 | }); 11 | return `New account created for ${name}`; 12 | } else { 13 | return "Account already exists"; 14 | } 15 | }; 16 | 17 | const credit = (name, money) => { 18 | if (_findAccount(name)) { 19 | _accounts.forEach(acc => { 20 | if (acc.name === name) { 21 | acc.monies = acc.monies + money; 22 | } 23 | }); 24 | } 25 | }; 26 | 27 | const debit = (name, money) => { 28 | if (_findAccount(name)) { 29 | _accounts.forEach(acc => { 30 | if (acc.name === name) { 31 | acc.monies = acc.monies - money; 32 | } 33 | }); 34 | } 35 | }; 36 | 37 | const getFunds = name => { 38 | if (_findAccount(name)) { 39 | return _accounts.find(acc => acc.name === name)["monies"]; 40 | } 41 | return "Account not found!"; 42 | }; 43 | 44 | module.exports = { 45 | createAccount, 46 | credit, 47 | debit, 48 | getFunds 49 | }; -------------------------------------------------------------------------------- /Section 4/code_4.2/LokiAdapter.js: -------------------------------------------------------------------------------- 1 | class LokiAdapter { 2 | constructor(lokiDb) { 3 | this.lokiDb = lokiDb; 4 | this.collection = null; 5 | this.op = null; 6 | } 7 | defaults(obj) { 8 | this.collection = Object.keys(obj)[0]; 9 | this.op = "INIT"; 10 | return this; 11 | } 12 | get(collection) { 13 | this.collection = this.lokiDb.getCollection(collection); 14 | return this; 15 | } 16 | push(data) { 17 | this.dataToPush = data; 18 | this.op = "WRITE"; 19 | return this; 20 | } 21 | value() { 22 | return this.collection.find(); 23 | } 24 | write() { 25 | if (this.op) { 26 | switch (this.op) { 27 | case "INIT": 28 | this.lokiDb.addCollection(this.collection); 29 | this.collection = null; 30 | this.op = null; 31 | break; 32 | case "WRITE": 33 | this.collection.insert(this.dataToPush); 34 | this.dataToPush = null; 35 | this.collection = null; 36 | this.op = null; 37 | break; 38 | } 39 | 40 | this.lokiDb.saveDatabase(); 41 | } 42 | 43 | return this; 44 | } 45 | } 46 | 47 | module.exports = LokiAdapter; -------------------------------------------------------------------------------- /Section 1/code_1.4/signup/UserPref.js: -------------------------------------------------------------------------------- 1 | class UserPref { 2 | constructor( 3 | userId, 4 | nickname, 5 | favouriteTopics, 6 | isSME, 7 | isModerator, 8 | isAdmin 9 | ) { 10 | return new Promise((resolve, reject) => { 11 | this.userId = userId; 12 | 13 | if (nickname) { 14 | this._setNickname(nickname); 15 | } 16 | 17 | if (favouriteTopics) { 18 | this._favTopics(favouriteTopics); 19 | } 20 | 21 | if (isSME) { 22 | this._setSME(isSME); 23 | } 24 | 25 | if (isModerator) { 26 | this._isModerator(isModerator); 27 | } 28 | 29 | if (isAdmin) { 30 | this._isAdmin(isAdmin); 31 | } 32 | 33 | resolve(true); 34 | }); 35 | } 36 | _setNickname(nickname) { 37 | console.log(`- Nickname (${nickname}) set...`); 38 | } 39 | _favTopics(topics) { 40 | console.log(`- User favourite topics (${topics.join(',')}) subscribed!`); 41 | } 42 | _setSME(topics) { 43 | if (topics) { 44 | console.log(`- User is now an SME for ${topics.join(',')}...`); 45 | } 46 | } 47 | _isModerator(opt) { 48 | if (opt) { 49 | console.log(`- User registered as a Moderator!`); 50 | } 51 | } 52 | _isAdmin() { 53 | console.log('- User is now an Administrator!'); 54 | } 55 | } 56 | 57 | module.exports = UserPref; -------------------------------------------------------------------------------- /Section 2/code_2.3/app.js: -------------------------------------------------------------------------------- 1 | const { 2 | readdir, 3 | readFile, 4 | writeFile 5 | } = require("fs"); 6 | const { 7 | join 8 | } = require("path"); 9 | const { 10 | promisify 11 | } = require("util"); 12 | const inbox = join(__dirname, "inbox"); 13 | const outbox = join(__dirname, "outbox"); 14 | 15 | const reverseText = str => 16 | Promise.resolve(str 17 | .split("") 18 | .reverse() 19 | .join("")); 20 | 21 | const readdirAsync = promisify(readdir); // Promisified version of readdir 22 | const readFileAsync = promisify(readFile); 23 | const writeFileAsync = promisify(writeFile); 24 | 25 | // Read and reverse contents of text files in a directory 26 | async function readReverseWrite(file) { 27 | try { 28 | const read = await readFileAsync(join(inbox, file), "utf8"); 29 | const reverse = await reverseText(read); 30 | await writeFileAsync(join(outbox, file), reverse); 31 | } catch (error) { 32 | throw Error(error); 33 | } finally { 34 | console.log(`${file} has been processed!`); 35 | } 36 | } 37 | 38 | async function processFiles() { 39 | try { 40 | const getAllFiles = await readdirAsync(inbox); 41 | const processAllFiles = getAllFiles.map(file => readReverseWrite(file)); 42 | await Promise.all(processAllFiles); 43 | } catch (error) { 44 | console.log(error); // Handle errors 45 | } finally { 46 | console.log("*** All files processed ***"); 47 | } 48 | } 49 | 50 | processFiles(); -------------------------------------------------------------------------------- /Section 2/code_2.4/async-generators/app.js: -------------------------------------------------------------------------------- 1 | const { 2 | readdir, 3 | readFile, 4 | writeFile 5 | } = require("fs"); 6 | const { 7 | join 8 | } = require("path"); 9 | const { 10 | promisify 11 | } = require("util"); 12 | const inbox = join(__dirname, "inbox"); 13 | const outbox = join(__dirname, "outbox"); 14 | 15 | const reverseText = str => 16 | Promise.resolve(str 17 | .split("") 18 | .reverse() 19 | .join("")); 20 | 21 | const readdirAsync = promisify(readdir); // Promisified version of readdir 22 | const readFileAsync = promisify(readFile); 23 | const writeFileAsync = promisify(writeFile); 24 | 25 | // Read and reverse contents of text files in a directory 26 | async function* getFilesIterator() { 27 | try { 28 | const readDirectory = await readdirAsync(inbox); 29 | for (const file of readDirectory) { 30 | yield file; 31 | } 32 | } catch (error) { 33 | throw Error(error); 34 | } 35 | } 36 | 37 | async function process() { 38 | try { 39 | const allFiles = await getFilesIterator(); // AsyncGenerator Object 40 | for await (const file of allFiles) { 41 | const read = await readFileAsync(join(inbox, file), "utf8"); 42 | const reverse = await reverseText(read); 43 | await writeFileAsync(join(outbox, file), reverse); 44 | console.log(`${file} has been processed!`); 45 | } 46 | } catch (error) { 47 | console.log(error); 48 | } finally { 49 | console.log("*** All files processed ***"); 50 | } 51 | } 52 | 53 | process(); -------------------------------------------------------------------------------- /Section 2/code_2.1/inbox/Writing_a_Book.txt: -------------------------------------------------------------------------------- 1 | WRITING A BOOK. 2 | 3 | 4 | "Let us write a book," they said; "but what shall it be about?" 5 | 6 | "A fairy story," said the elder sister. 7 | 8 | "A book about kings and queens," said the other. 9 | 10 | "Oh, no," said the brother, "let's write about animals." 11 | 12 | "We will write about them all," they cried together. So they put the 13 | paper, and pens, and ink ready. The elder sister took up a fairy story 14 | and looked at it, and put it down again. 15 | 16 | "I have never known any fairies," she said, "except in books; but, of 17 | course, it would not do to put one book inside another--anyone could do 18 | that." 19 | 20 | "I shall not begin to-day," the little one said, "for I must know a few 21 | kings and queens before I write about them, or I may say something 22 | foolish." 23 | 24 | "I shall write about the pig, and the pony, and the white rabbit," said 25 | the brother; "but first I must think a bit. It would never do to write 26 | a book without thinking." 27 | 28 | Then the elder sister took up the fairy story again, to see how many 29 | things were left out, for those, she thought, would do to go into her 30 | book. The little one said to herself, "Really, it is no good thinking 31 | about kings and queens until I have known some, so I must wait;" and 32 | while the brother was considering about the pig, and the pony, and the 33 | white rabbit, he fell asleep. 34 | 35 | So the book is not written yet, but when it is we shall know a great 36 | deal. 37 | -------------------------------------------------------------------------------- /Section 2/code_2.2/inbox/Writing_a_Book.txt: -------------------------------------------------------------------------------- 1 | WRITING A BOOK. 2 | 3 | 4 | "Let us write a book," they said; "but what shall it be about?" 5 | 6 | "A fairy story," said the elder sister. 7 | 8 | "A book about kings and queens," said the other. 9 | 10 | "Oh, no," said the brother, "let's write about animals." 11 | 12 | "We will write about them all," they cried together. So they put the 13 | paper, and pens, and ink ready. The elder sister took up a fairy story 14 | and looked at it, and put it down again. 15 | 16 | "I have never known any fairies," she said, "except in books; but, of 17 | course, it would not do to put one book inside another--anyone could do 18 | that." 19 | 20 | "I shall not begin to-day," the little one said, "for I must know a few 21 | kings and queens before I write about them, or I may say something 22 | foolish." 23 | 24 | "I shall write about the pig, and the pony, and the white rabbit," said 25 | the brother; "but first I must think a bit. It would never do to write 26 | a book without thinking." 27 | 28 | Then the elder sister took up the fairy story again, to see how many 29 | things were left out, for those, she thought, would do to go into her 30 | book. The little one said to herself, "Really, it is no good thinking 31 | about kings and queens until I have known some, so I must wait;" and 32 | while the brother was considering about the pig, and the pony, and the 33 | white rabbit, he fell asleep. 34 | 35 | So the book is not written yet, but when it is we shall know a great 36 | deal. 37 | -------------------------------------------------------------------------------- /Section 2/code_2.3/inbox/Writing_a_Book.txt: -------------------------------------------------------------------------------- 1 | WRITING A BOOK. 2 | 3 | 4 | "Let us write a book," they said; "but what shall it be about?" 5 | 6 | "A fairy story," said the elder sister. 7 | 8 | "A book about kings and queens," said the other. 9 | 10 | "Oh, no," said the brother, "let's write about animals." 11 | 12 | "We will write about them all," they cried together. So they put the 13 | paper, and pens, and ink ready. The elder sister took up a fairy story 14 | and looked at it, and put it down again. 15 | 16 | "I have never known any fairies," she said, "except in books; but, of 17 | course, it would not do to put one book inside another--anyone could do 18 | that." 19 | 20 | "I shall not begin to-day," the little one said, "for I must know a few 21 | kings and queens before I write about them, or I may say something 22 | foolish." 23 | 24 | "I shall write about the pig, and the pony, and the white rabbit," said 25 | the brother; "but first I must think a bit. It would never do to write 26 | a book without thinking." 27 | 28 | Then the elder sister took up the fairy story again, to see how many 29 | things were left out, for those, she thought, would do to go into her 30 | book. The little one said to herself, "Really, it is no good thinking 31 | about kings and queens until I have known some, so I must wait;" and 32 | while the brother was considering about the pig, and the pony, and the 33 | white rabbit, he fell asleep. 34 | 35 | So the book is not written yet, but when it is we shall know a great 36 | deal. 37 | -------------------------------------------------------------------------------- /Section 2/code_2.1/outbox/Writing_a_Book.txt: -------------------------------------------------------------------------------- 1 | 2 | .laed 3 | taerg a wonk llahs ew si ti nehw tub ,tey nettirw ton si koob eht oS 4 | 5 | .peelsa llef eh ,tibbar etihw 6 | eht dna ,ynop eht dna ,gip eht tuoba gniredisnoc saw rehtorb eht elihw 7 | dna ";tiaw tsum I os ,emos nwonk evah I litnu sneeuq dna sgnik tuoba 8 | gnikniht doog on si ti ,yllaeR" ,flesreh ot dias eno elttil ehT .koob 9 | reh otni og ot od dluow ,thguoht ehs ,esoht rof ,tuo tfel erew sgniht 10 | ynam woh ees ot ,niaga yrots yriaf eht pu koot retsis redle eht nehT 11 | 12 | ".gnikniht tuohtiw koob a 13 | etirw ot od reven dluow tI .tib a kniht tsum I tsrif tub" ;rehtorb eht 14 | dias ",tibbar etihw eht dna ,ynop eht dna ,gip eht tuoba etirw llahs I" 15 | 16 | ".hsiloof 17 | gnihtemos yas yam I ro ,meht tuoba etirw I erofeb sneeuq dna sgnik 18 | wef a wonk tsum I rof" ,dias eno elttil eht ",yad-ot nigeb ton llahs I" 19 | 20 | ".taht 21 | od dluoc enoyna--rehtona edisni koob eno tup ot od ton dluow ti ,esruoc 22 | fo ,tub ;skoob ni tpecxe" ,dias ehs ",seiriaf yna nwonk reven evah I" 23 | 24 | .niaga nwod ti tup dna ,ti ta dekool dna 25 | yrots yriaf a pu koot retsis redle ehT .ydaer kni dna ,snep dna ,repap 26 | eht tup yeht oS .rehtegot deirc yeht ",lla meht tuoba etirw lliw eW" 27 | 28 | ".slamina tuoba etirw s'tel" ,rehtorb eht dias ",on ,hO" 29 | 30 | .rehto eht dias ",sneeuq dna sgnik tuoba koob A" 31 | 32 | .retsis redle eht dias ",yrots yriaf A" 33 | 34 | "?tuoba eb ti llahs tahw tub" ;dias yeht ",koob a etirw su teL" 35 | 36 | 37 | .KOOB A GNITIRW -------------------------------------------------------------------------------- /Section 2/code_2.2/outbox/Writing_a_Book.txt: -------------------------------------------------------------------------------- 1 | 2 | .laed 3 | taerg a wonk llahs ew si ti nehw tub ,tey nettirw ton si koob eht oS 4 | 5 | .peelsa llef eh ,tibbar etihw 6 | eht dna ,ynop eht dna ,gip eht tuoba gniredisnoc saw rehtorb eht elihw 7 | dna ";tiaw tsum I os ,emos nwonk evah I litnu sneeuq dna sgnik tuoba 8 | gnikniht doog on si ti ,yllaeR" ,flesreh ot dias eno elttil ehT .koob 9 | reh otni og ot od dluow ,thguoht ehs ,esoht rof ,tuo tfel erew sgniht 10 | ynam woh ees ot ,niaga yrots yriaf eht pu koot retsis redle eht nehT 11 | 12 | ".gnikniht tuohtiw koob a 13 | etirw ot od reven dluow tI .tib a kniht tsum I tsrif tub" ;rehtorb eht 14 | dias ",tibbar etihw eht dna ,ynop eht dna ,gip eht tuoba etirw llahs I" 15 | 16 | ".hsiloof 17 | gnihtemos yas yam I ro ,meht tuoba etirw I erofeb sneeuq dna sgnik 18 | wef a wonk tsum I rof" ,dias eno elttil eht ",yad-ot nigeb ton llahs I" 19 | 20 | ".taht 21 | od dluoc enoyna--rehtona edisni koob eno tup ot od ton dluow ti ,esruoc 22 | fo ,tub ;skoob ni tpecxe" ,dias ehs ",seiriaf yna nwonk reven evah I" 23 | 24 | .niaga nwod ti tup dna ,ti ta dekool dna 25 | yrots yriaf a pu koot retsis redle ehT .ydaer kni dna ,snep dna ,repap 26 | eht tup yeht oS .rehtegot deirc yeht ",lla meht tuoba etirw lliw eW" 27 | 28 | ".slamina tuoba etirw s'tel" ,rehtorb eht dias ",on ,hO" 29 | 30 | .rehto eht dias ",sneeuq dna sgnik tuoba koob A" 31 | 32 | .retsis redle eht dias ",yrots yriaf A" 33 | 34 | "?tuoba eb ti llahs tahw tub" ;dias yeht ",koob a etirw su teL" 35 | 36 | 37 | .KOOB A GNITIRW -------------------------------------------------------------------------------- /Section 2/code_2.3/outbox/Writing_a_Book.txt: -------------------------------------------------------------------------------- 1 | 2 | .laed 3 | taerg a wonk llahs ew si ti nehw tub ,tey nettirw ton si koob eht oS 4 | 5 | .peelsa llef eh ,tibbar etihw 6 | eht dna ,ynop eht dna ,gip eht tuoba gniredisnoc saw rehtorb eht elihw 7 | dna ";tiaw tsum I os ,emos nwonk evah I litnu sneeuq dna sgnik tuoba 8 | gnikniht doog on si ti ,yllaeR" ,flesreh ot dias eno elttil ehT .koob 9 | reh otni og ot od dluow ,thguoht ehs ,esoht rof ,tuo tfel erew sgniht 10 | ynam woh ees ot ,niaga yrots yriaf eht pu koot retsis redle eht nehT 11 | 12 | ".gnikniht tuohtiw koob a 13 | etirw ot od reven dluow tI .tib a kniht tsum I tsrif tub" ;rehtorb eht 14 | dias ",tibbar etihw eht dna ,ynop eht dna ,gip eht tuoba etirw llahs I" 15 | 16 | ".hsiloof 17 | gnihtemos yas yam I ro ,meht tuoba etirw I erofeb sneeuq dna sgnik 18 | wef a wonk tsum I rof" ,dias eno elttil eht ",yad-ot nigeb ton llahs I" 19 | 20 | ".taht 21 | od dluoc enoyna--rehtona edisni koob eno tup ot od ton dluow ti ,esruoc 22 | fo ,tub ;skoob ni tpecxe" ,dias ehs ",seiriaf yna nwonk reven evah I" 23 | 24 | .niaga nwod ti tup dna ,ti ta dekool dna 25 | yrots yriaf a pu koot retsis redle ehT .ydaer kni dna ,snep dna ,repap 26 | eht tup yeht oS .rehtegot deirc yeht ",lla meht tuoba etirw lliw eW" 27 | 28 | ".slamina tuoba etirw s'tel" ,rehtorb eht dias ",on ,hO" 29 | 30 | .rehto eht dias ",sneeuq dna sgnik tuoba koob A" 31 | 32 | .retsis redle eht dias ",yrots yriaf A" 33 | 34 | "?tuoba eb ti llahs tahw tub" ;dias yeht ",koob a etirw su teL" 35 | 36 | 37 | .KOOB A GNITIRW -------------------------------------------------------------------------------- /Section 2/code_2.4/async-generators/inbox/Writing_a_Book.txt: -------------------------------------------------------------------------------- 1 | WRITING A BOOK. 2 | 3 | 4 | "Let us write a book," they said; "but what shall it be about?" 5 | 6 | "A fairy story," said the elder sister. 7 | 8 | "A book about kings and queens," said the other. 9 | 10 | "Oh, no," said the brother, "let's write about animals." 11 | 12 | "We will write about them all," they cried together. So they put the 13 | paper, and pens, and ink ready. The elder sister took up a fairy story 14 | and looked at it, and put it down again. 15 | 16 | "I have never known any fairies," she said, "except in books; but, of 17 | course, it would not do to put one book inside another--anyone could do 18 | that." 19 | 20 | "I shall not begin to-day," the little one said, "for I must know a few 21 | kings and queens before I write about them, or I may say something 22 | foolish." 23 | 24 | "I shall write about the pig, and the pony, and the white rabbit," said 25 | the brother; "but first I must think a bit. It would never do to write 26 | a book without thinking." 27 | 28 | Then the elder sister took up the fairy story again, to see how many 29 | things were left out, for those, she thought, would do to go into her 30 | book. The little one said to herself, "Really, it is no good thinking 31 | about kings and queens until I have known some, so I must wait;" and 32 | while the brother was considering about the pig, and the pony, and the 33 | white rabbit, he fell asleep. 34 | 35 | So the book is not written yet, but when it is we shall know a great 36 | deal. 37 | -------------------------------------------------------------------------------- /Section 2/code_2.4/async-generators/outbox/Writing_a_Book.txt: -------------------------------------------------------------------------------- 1 | 2 | .laed 3 | taerg a wonk llahs ew si ti nehw tub ,tey nettirw ton si koob eht oS 4 | 5 | .peelsa llef eh ,tibbar etihw 6 | eht dna ,ynop eht dna ,gip eht tuoba gniredisnoc saw rehtorb eht elihw 7 | dna ";tiaw tsum I os ,emos nwonk evah I litnu sneeuq dna sgnik tuoba 8 | gnikniht doog on si ti ,yllaeR" ,flesreh ot dias eno elttil ehT .koob 9 | reh otni og ot od dluow ,thguoht ehs ,esoht rof ,tuo tfel erew sgniht 10 | ynam woh ees ot ,niaga yrots yriaf eht pu koot retsis redle eht nehT 11 | 12 | ".gnikniht tuohtiw koob a 13 | etirw ot od reven dluow tI .tib a kniht tsum I tsrif tub" ;rehtorb eht 14 | dias ",tibbar etihw eht dna ,ynop eht dna ,gip eht tuoba etirw llahs I" 15 | 16 | ".hsiloof 17 | gnihtemos yas yam I ro ,meht tuoba etirw I erofeb sneeuq dna sgnik 18 | wef a wonk tsum I rof" ,dias eno elttil eht ",yad-ot nigeb ton llahs I" 19 | 20 | ".taht 21 | od dluoc enoyna--rehtona edisni koob eno tup ot od ton dluow ti ,esruoc 22 | fo ,tub ;skoob ni tpecxe" ,dias ehs ",seiriaf yna nwonk reven evah I" 23 | 24 | .niaga nwod ti tup dna ,ti ta dekool dna 25 | yrots yriaf a pu koot retsis redle ehT .ydaer kni dna ,snep dna ,repap 26 | eht tup yeht oS .rehtegot deirc yeht ",lla meht tuoba etirw lliw eW" 27 | 28 | ".slamina tuoba etirw s'tel" ,rehtorb eht dias ",on ,hO" 29 | 30 | .rehto eht dias ",sneeuq dna sgnik tuoba koob A" 31 | 32 | .retsis redle eht dias ",yrots yriaf A" 33 | 34 | "?tuoba eb ti llahs tahw tub" ;dias yeht ",koob a etirw su teL" 35 | 36 | 37 | .KOOB A GNITIRW -------------------------------------------------------------------------------- /Section 5/code_5.2/dbs.json: -------------------------------------------------------------------------------- 1 | {"filename":"/Users/sachinbhatnagar/Dropbox/My Courses/Packt - NodeJS Design Patterns/code/Section 5/5.2 - Command/code/dbs.json","collections":[{"name":"posts","data":[{"title":"My First Post","content":"Hello everyone, this is my first post!","timestamp":"2019-02-10T06:24:47.276Z","id":1549779887276,"meta":{"revision":0,"created":1549779887276,"version":0},"$loki":1},{"title":"About Design Patterns","content":"So, I'm building a course on design patterns for Node.js","timestamp":"2019-02-10T06:24:47.277Z","id":1549779887277,"meta":{"revision":0,"created":1549779887277,"version":0},"$loki":2}],"idIndex":[1,2],"binaryIndices":{},"constraints":null,"uniqueNames":[],"transforms":{},"objType":"posts","dirty":false,"cachedIndex":null,"cachedBinaryIndex":null,"cachedData":null,"adaptiveBinaryIndices":true,"transactional":false,"cloneObjects":false,"cloneMethod":"parse-stringify","asyncListeners":false,"disableMeta":false,"disableChangesApi":true,"disableDeltaChangesApi":true,"autoupdate":false,"serializableIndices":true,"ttl":null,"maxId":2,"DynamicViews":[],"events":{"insert":[],"update":[],"pre-insert":[],"pre-update":[],"close":[],"flushbuffer":[],"error":[],"delete":[null],"warning":[null]},"changes":[]}],"databaseVersion":1.5,"engineVersion":1.5,"autosave":false,"autosaveInterval":5000,"autosaveHandle":null,"throttledSaves":true,"options":{"serializationMethod":"normal","destructureDelimiter":"$<\n"},"persistenceMethod":"fs","persistenceAdapter":null,"verbose":false,"events":{"init":[null],"loaded":[],"flushChanges":[],"close":[],"changes":[],"warning":[]},"ENV":"NODEJS"} -------------------------------------------------------------------------------- /Section 3/code_3.2/Bank.js: -------------------------------------------------------------------------------- 1 | let accounts = []; 2 | const findAccount = Symbol("findAccount"); 3 | const trimName = name => 4 | `XXXXXXXX${name 5 | .replace(/\s/g, "") 6 | .slice(-4) 7 | .toUpperCase()}`; 8 | 9 | const logger = data => console.log(data); // Logs activity to the console 10 | 11 | class Bank { 12 | config({ 13 | logger 14 | }) { 15 | this.logger = logger; 16 | } 17 | [findAccount](name) { 18 | return accounts.find(acc => acc.name === name); 19 | } 20 | createAccount(name, monies = 0) { 21 | if (!this[findAccount](name)) { 22 | accounts.push({ 23 | name, 24 | monies 25 | }); 26 | 27 | if (this.logger) { 28 | this.logger.write(`Account created for ${trimName(name)}`); 29 | } 30 | } else { 31 | console.log("An account already exists"); 32 | } 33 | } 34 | credit(name, amount) { 35 | if (this[findAccount](name)) { 36 | accounts.forEach(acc => { 37 | if (acc.name === name) { 38 | acc.monies = acc.monies + amount; 39 | } 40 | }); 41 | 42 | if (this.logger) { 43 | this.logger.write(`${amount} credited to ${trimName(name)}`); 44 | } 45 | } 46 | } 47 | debit(name, amount) { 48 | if (this[findAccount](name)) { 49 | accounts.forEach(acc => { 50 | acc.monies = acc.monies - amount; 51 | }); 52 | } 53 | 54 | if (this.logger) { 55 | this.logger.write(`${amount} debited from ${trimName(name)}`); 56 | } 57 | } 58 | getFunds(name) { 59 | if (this[findAccount](name)) { 60 | return accounts.find(acc => acc.name === name)["monies"]; 61 | } 62 | return "Account not found!"; 63 | } 64 | } 65 | 66 | module.exports = new Bank(); -------------------------------------------------------------------------------- /Section 2/code_2.1/inbox/The_Sandy_Cat.txt: -------------------------------------------------------------------------------- 1 | THE SANDY CAT. 2 | 3 | 4 | The sandy cat sat by the kitchen fire. Yesterday it had had no supper; 5 | this morning everyone had forgotten it. All night it had caught no 6 | mice; all day as yet it had tasted no milk. A little grey mouse, a 7 | saucerful of milk, a few fish or chicken bones, would have satisfied 8 | it; but no grey mouse, with its soft stringy tail behind it, ran across 9 | the floor; no milk was near, no chicken bones, no fish, no anything. 10 | The serving-maid had been washing clothes, and was hanging them out to 11 | dry. The children had loitered on their way to school, and were 12 | wondering what the master would say to them. The father had gone to the 13 | fair to help a neighbour to choose a horse. The mother sat making a 14 | patchwork quilt. No one thought of the sandy cat; it sat by the fire 15 | alone and hungry. 16 | 17 | At last the clothes were all a-drying, the children had been scolded, 18 | and sat learning a lesson for the morrow. The father came from the 19 | fair, and the patchwork quilt was put away. The serving-maid put on a 20 | white apron with a frill, and a clean cap, then taking the sandy cat in 21 | her arms, said, "Pussy, shall we go into the garden?" So they went and 22 | walked up and down, up and down the pathway, till at last they stopped 23 | before a rose tree; the serving-maid held up the cat to smell the 24 | roses, but with one long bound it leaped from her arms and 25 | away--away--away. 26 | 27 | Whither? 28 | 29 | Ah, dear children, I cannot tell, for I was not there to see; but if 30 | ever you are a sandy cat you will know that it is a terrible thing to 31 | be asked to smell roses when you are longing for a saucerful of milk 32 | and a grey mouse with a soft stringy tail. 33 | 34 | -------------------------------------------------------------------------------- /Section 2/code_2.1/outbox/The_Sandy_Cat.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | .liat ygnirts tfos a htiw esuom yerg a dna 4 | klim fo lufrecuas a rof gnignol era uoy nehw sesor llems ot deksa eb 5 | ot gniht elbirret a si ti taht wonk lliw uoy tac ydnas a era uoy reve 6 | fi tub ;ees ot ereht ton saw I rof ,llet tonnac I ,nerdlihc raed ,hA 7 | 8 | ?rehtihW 9 | 10 | .yawa--yawa--yawa 11 | dna smra reh morf depael ti dnuob gnol eno htiw tub ,sesor 12 | eht llems ot tac eht pu dleh diam-gnivres eht ;eert esor a erofeb 13 | deppots yeht tsal ta llit ,yawhtap eht nwod dna pu ,nwod dna pu deklaw 14 | dna tnew yeht oS "?nedrag eht otni og ew llahs ,yssuP" ,dias ,smra reh 15 | ni tac ydnas eht gnikat neht ,pac naelc a dna ,llirf a htiw norpa etihw 16 | a no tup diam-gnivres ehT .yawa tup saw tliuq krowhctap eht dna ,riaf 17 | eht morf emac rehtaf ehT .worrom eht rof nossel a gninrael tas dna 18 | ,dedlocs neeb dah nerdlihc eht ,gniyrd-a lla erew sehtolc eht tsal tA 19 | 20 | .yrgnuh dna enola 21 | erif eht yb tas ti ;tac ydnas eht fo thguoht eno oN .tliuq krowhctap 22 | a gnikam tas rehtom ehT .esroh a esoohc ot ruobhgien a pleh ot riaf 23 | eht ot enog dah rehtaf ehT .meht ot yas dluow retsam eht tahw gnirednow 24 | erew dna ,loohcs ot yaw rieht no deretiol dah nerdlihc ehT .yrd 25 | ot tuo meht gnignah saw dna ,sehtolc gnihsaw neeb dah diam-gnivres ehT 26 | .gnihtyna on ,hsif on ,senob nekcihc on ,raen saw klim on ;roolf eht 27 | ssorca nar ,ti dniheb liat ygnirts tfos sti htiw ,esuom yerg on tub ;ti 28 | deifsitas evah dluow ,senob nekcihc ro hsif wef a ,klim fo lufrecuas 29 | a ,esuom yerg elttil A .klim on detsat dah ti tey sa yad lla ;ecim 30 | on thguac dah ti thgin llA .ti nettogrof dah enoyreve gninrom siht 31 | ;reppus on dah dah ti yadretseY .erif nehctik eht yb tas tac ydnas ehT 32 | 33 | 34 | .TAC YDNAS EHT -------------------------------------------------------------------------------- /Section 2/code_2.2/inbox/The_Sandy_Cat.txt: -------------------------------------------------------------------------------- 1 | THE SANDY CAT. 2 | 3 | 4 | The sandy cat sat by the kitchen fire. Yesterday it had had no supper; 5 | this morning everyone had forgotten it. All night it had caught no 6 | mice; all day as yet it had tasted no milk. A little grey mouse, a 7 | saucerful of milk, a few fish or chicken bones, would have satisfied 8 | it; but no grey mouse, with its soft stringy tail behind it, ran across 9 | the floor; no milk was near, no chicken bones, no fish, no anything. 10 | The serving-maid had been washing clothes, and was hanging them out to 11 | dry. The children had loitered on their way to school, and were 12 | wondering what the master would say to them. The father had gone to the 13 | fair to help a neighbour to choose a horse. The mother sat making a 14 | patchwork quilt. No one thought of the sandy cat; it sat by the fire 15 | alone and hungry. 16 | 17 | At last the clothes were all a-drying, the children had been scolded, 18 | and sat learning a lesson for the morrow. The father came from the 19 | fair, and the patchwork quilt was put away. The serving-maid put on a 20 | white apron with a frill, and a clean cap, then taking the sandy cat in 21 | her arms, said, "Pussy, shall we go into the garden?" So they went and 22 | walked up and down, up and down the pathway, till at last they stopped 23 | before a rose tree; the serving-maid held up the cat to smell the 24 | roses, but with one long bound it leaped from her arms and 25 | away--away--away. 26 | 27 | Whither? 28 | 29 | Ah, dear children, I cannot tell, for I was not there to see; but if 30 | ever you are a sandy cat you will know that it is a terrible thing to 31 | be asked to smell roses when you are longing for a saucerful of milk 32 | and a grey mouse with a soft stringy tail. 33 | 34 | -------------------------------------------------------------------------------- /Section 2/code_2.2/outbox/The_Sandy_Cat.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | .liat ygnirts tfos a htiw esuom yerg a dna 4 | klim fo lufrecuas a rof gnignol era uoy nehw sesor llems ot deksa eb 5 | ot gniht elbirret a si ti taht wonk lliw uoy tac ydnas a era uoy reve 6 | fi tub ;ees ot ereht ton saw I rof ,llet tonnac I ,nerdlihc raed ,hA 7 | 8 | ?rehtihW 9 | 10 | .yawa--yawa--yawa 11 | dna smra reh morf depael ti dnuob gnol eno htiw tub ,sesor 12 | eht llems ot tac eht pu dleh diam-gnivres eht ;eert esor a erofeb 13 | deppots yeht tsal ta llit ,yawhtap eht nwod dna pu ,nwod dna pu deklaw 14 | dna tnew yeht oS "?nedrag eht otni og ew llahs ,yssuP" ,dias ,smra reh 15 | ni tac ydnas eht gnikat neht ,pac naelc a dna ,llirf a htiw norpa etihw 16 | a no tup diam-gnivres ehT .yawa tup saw tliuq krowhctap eht dna ,riaf 17 | eht morf emac rehtaf ehT .worrom eht rof nossel a gninrael tas dna 18 | ,dedlocs neeb dah nerdlihc eht ,gniyrd-a lla erew sehtolc eht tsal tA 19 | 20 | .yrgnuh dna enola 21 | erif eht yb tas ti ;tac ydnas eht fo thguoht eno oN .tliuq krowhctap 22 | a gnikam tas rehtom ehT .esroh a esoohc ot ruobhgien a pleh ot riaf 23 | eht ot enog dah rehtaf ehT .meht ot yas dluow retsam eht tahw gnirednow 24 | erew dna ,loohcs ot yaw rieht no deretiol dah nerdlihc ehT .yrd 25 | ot tuo meht gnignah saw dna ,sehtolc gnihsaw neeb dah diam-gnivres ehT 26 | .gnihtyna on ,hsif on ,senob nekcihc on ,raen saw klim on ;roolf eht 27 | ssorca nar ,ti dniheb liat ygnirts tfos sti htiw ,esuom yerg on tub ;ti 28 | deifsitas evah dluow ,senob nekcihc ro hsif wef a ,klim fo lufrecuas 29 | a ,esuom yerg elttil A .klim on detsat dah ti tey sa yad lla ;ecim 30 | on thguac dah ti thgin llA .ti nettogrof dah enoyreve gninrom siht 31 | ;reppus on dah dah ti yadretseY .erif nehctik eht yb tas tac ydnas ehT 32 | 33 | 34 | .TAC YDNAS EHT -------------------------------------------------------------------------------- /Section 2/code_2.3/inbox/The_Sandy_Cat.txt: -------------------------------------------------------------------------------- 1 | THE SANDY CAT. 2 | 3 | 4 | The sandy cat sat by the kitchen fire. Yesterday it had had no supper; 5 | this morning everyone had forgotten it. All night it had caught no 6 | mice; all day as yet it had tasted no milk. A little grey mouse, a 7 | saucerful of milk, a few fish or chicken bones, would have satisfied 8 | it; but no grey mouse, with its soft stringy tail behind it, ran across 9 | the floor; no milk was near, no chicken bones, no fish, no anything. 10 | The serving-maid had been washing clothes, and was hanging them out to 11 | dry. The children had loitered on their way to school, and were 12 | wondering what the master would say to them. The father had gone to the 13 | fair to help a neighbour to choose a horse. The mother sat making a 14 | patchwork quilt. No one thought of the sandy cat; it sat by the fire 15 | alone and hungry. 16 | 17 | At last the clothes were all a-drying, the children had been scolded, 18 | and sat learning a lesson for the morrow. The father came from the 19 | fair, and the patchwork quilt was put away. The serving-maid put on a 20 | white apron with a frill, and a clean cap, then taking the sandy cat in 21 | her arms, said, "Pussy, shall we go into the garden?" So they went and 22 | walked up and down, up and down the pathway, till at last they stopped 23 | before a rose tree; the serving-maid held up the cat to smell the 24 | roses, but with one long bound it leaped from her arms and 25 | away--away--away. 26 | 27 | Whither? 28 | 29 | Ah, dear children, I cannot tell, for I was not there to see; but if 30 | ever you are a sandy cat you will know that it is a terrible thing to 31 | be asked to smell roses when you are longing for a saucerful of milk 32 | and a grey mouse with a soft stringy tail. 33 | 34 | -------------------------------------------------------------------------------- /Section 2/code_2.3/outbox/The_Sandy_Cat.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | .liat ygnirts tfos a htiw esuom yerg a dna 4 | klim fo lufrecuas a rof gnignol era uoy nehw sesor llems ot deksa eb 5 | ot gniht elbirret a si ti taht wonk lliw uoy tac ydnas a era uoy reve 6 | fi tub ;ees ot ereht ton saw I rof ,llet tonnac I ,nerdlihc raed ,hA 7 | 8 | ?rehtihW 9 | 10 | .yawa--yawa--yawa 11 | dna smra reh morf depael ti dnuob gnol eno htiw tub ,sesor 12 | eht llems ot tac eht pu dleh diam-gnivres eht ;eert esor a erofeb 13 | deppots yeht tsal ta llit ,yawhtap eht nwod dna pu ,nwod dna pu deklaw 14 | dna tnew yeht oS "?nedrag eht otni og ew llahs ,yssuP" ,dias ,smra reh 15 | ni tac ydnas eht gnikat neht ,pac naelc a dna ,llirf a htiw norpa etihw 16 | a no tup diam-gnivres ehT .yawa tup saw tliuq krowhctap eht dna ,riaf 17 | eht morf emac rehtaf ehT .worrom eht rof nossel a gninrael tas dna 18 | ,dedlocs neeb dah nerdlihc eht ,gniyrd-a lla erew sehtolc eht tsal tA 19 | 20 | .yrgnuh dna enola 21 | erif eht yb tas ti ;tac ydnas eht fo thguoht eno oN .tliuq krowhctap 22 | a gnikam tas rehtom ehT .esroh a esoohc ot ruobhgien a pleh ot riaf 23 | eht ot enog dah rehtaf ehT .meht ot yas dluow retsam eht tahw gnirednow 24 | erew dna ,loohcs ot yaw rieht no deretiol dah nerdlihc ehT .yrd 25 | ot tuo meht gnignah saw dna ,sehtolc gnihsaw neeb dah diam-gnivres ehT 26 | .gnihtyna on ,hsif on ,senob nekcihc on ,raen saw klim on ;roolf eht 27 | ssorca nar ,ti dniheb liat ygnirts tfos sti htiw ,esuom yerg on tub ;ti 28 | deifsitas evah dluow ,senob nekcihc ro hsif wef a ,klim fo lufrecuas 29 | a ,esuom yerg elttil A .klim on detsat dah ti tey sa yad lla ;ecim 30 | on thguac dah ti thgin llA .ti nettogrof dah enoyreve gninrom siht 31 | ;reppus on dah dah ti yadretseY .erif nehctik eht yb tas tac ydnas ehT 32 | 33 | 34 | .TAC YDNAS EHT -------------------------------------------------------------------------------- /Section 2/code_2.4/async-generators/inbox/The_Sandy_Cat.txt: -------------------------------------------------------------------------------- 1 | THE SANDY CAT. 2 | 3 | 4 | The sandy cat sat by the kitchen fire. Yesterday it had had no supper; 5 | this morning everyone had forgotten it. All night it had caught no 6 | mice; all day as yet it had tasted no milk. A little grey mouse, a 7 | saucerful of milk, a few fish or chicken bones, would have satisfied 8 | it; but no grey mouse, with its soft stringy tail behind it, ran across 9 | the floor; no milk was near, no chicken bones, no fish, no anything. 10 | The serving-maid had been washing clothes, and was hanging them out to 11 | dry. The children had loitered on their way to school, and were 12 | wondering what the master would say to them. The father had gone to the 13 | fair to help a neighbour to choose a horse. The mother sat making a 14 | patchwork quilt. No one thought of the sandy cat; it sat by the fire 15 | alone and hungry. 16 | 17 | At last the clothes were all a-drying, the children had been scolded, 18 | and sat learning a lesson for the morrow. The father came from the 19 | fair, and the patchwork quilt was put away. The serving-maid put on a 20 | white apron with a frill, and a clean cap, then taking the sandy cat in 21 | her arms, said, "Pussy, shall we go into the garden?" So they went and 22 | walked up and down, up and down the pathway, till at last they stopped 23 | before a rose tree; the serving-maid held up the cat to smell the 24 | roses, but with one long bound it leaped from her arms and 25 | away--away--away. 26 | 27 | Whither? 28 | 29 | Ah, dear children, I cannot tell, for I was not there to see; but if 30 | ever you are a sandy cat you will know that it is a terrible thing to 31 | be asked to smell roses when you are longing for a saucerful of milk 32 | and a grey mouse with a soft stringy tail. 33 | 34 | -------------------------------------------------------------------------------- /Section 2/code_2.4/async-generators/outbox/The_Sandy_Cat.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | .liat ygnirts tfos a htiw esuom yerg a dna 4 | klim fo lufrecuas a rof gnignol era uoy nehw sesor llems ot deksa eb 5 | ot gniht elbirret a si ti taht wonk lliw uoy tac ydnas a era uoy reve 6 | fi tub ;ees ot ereht ton saw I rof ,llet tonnac I ,nerdlihc raed ,hA 7 | 8 | ?rehtihW 9 | 10 | .yawa--yawa--yawa 11 | dna smra reh morf depael ti dnuob gnol eno htiw tub ,sesor 12 | eht llems ot tac eht pu dleh diam-gnivres eht ;eert esor a erofeb 13 | deppots yeht tsal ta llit ,yawhtap eht nwod dna pu ,nwod dna pu deklaw 14 | dna tnew yeht oS "?nedrag eht otni og ew llahs ,yssuP" ,dias ,smra reh 15 | ni tac ydnas eht gnikat neht ,pac naelc a dna ,llirf a htiw norpa etihw 16 | a no tup diam-gnivres ehT .yawa tup saw tliuq krowhctap eht dna ,riaf 17 | eht morf emac rehtaf ehT .worrom eht rof nossel a gninrael tas dna 18 | ,dedlocs neeb dah nerdlihc eht ,gniyrd-a lla erew sehtolc eht tsal tA 19 | 20 | .yrgnuh dna enola 21 | erif eht yb tas ti ;tac ydnas eht fo thguoht eno oN .tliuq krowhctap 22 | a gnikam tas rehtom ehT .esroh a esoohc ot ruobhgien a pleh ot riaf 23 | eht ot enog dah rehtaf ehT .meht ot yas dluow retsam eht tahw gnirednow 24 | erew dna ,loohcs ot yaw rieht no deretiol dah nerdlihc ehT .yrd 25 | ot tuo meht gnignah saw dna ,sehtolc gnihsaw neeb dah diam-gnivres ehT 26 | .gnihtyna on ,hsif on ,senob nekcihc on ,raen saw klim on ;roolf eht 27 | ssorca nar ,ti dniheb liat ygnirts tfos sti htiw ,esuom yerg on tub ;ti 28 | deifsitas evah dluow ,senob nekcihc ro hsif wef a ,klim fo lufrecuas 29 | a ,esuom yerg elttil A .klim on detsat dah ti tey sa yad lla ;ecim 30 | on thguac dah ti thgin llA .ti nettogrof dah enoyreve gninrom siht 31 | ;reppus on dah dah ti yadretseY .erif nehctik eht yb tas tac ydnas ehT 32 | 33 | 34 | .TAC YDNAS EHT -------------------------------------------------------------------------------- /Section 2/code_2.1/inbox/The_Wooden_Doll.txt: -------------------------------------------------------------------------------- 1 | THE WOODEN DOLL. 2 | 3 | 4 | The wooden doll had no peace. My dears, if ever you are a doll, hope to 5 | be a rag doll, or a wax doll, or a doll full of sawdust apt to ooze 6 | out, or a china doll easy to break--anything in the world rather than a 7 | good strong wooden doll with a painted head and movable joints, for 8 | that is indeed a sad thing to be. Many a time the poor wooden doll 9 | wished it were a tin train, or a box of soldiers, or a woolly lamb, or 10 | anything on earth rather than what it was. It never had any peace; it 11 | was taken up and put down at all manners of odd moments, made to go to 12 | bed when the children went to bed, to get up when they got up, be 13 | bathed when they were bathed, dressed when they were dressed, taken out 14 | in all weathers, stuffed into their satchels when they went to school, 15 | left about in corners, dropped on stairs, forgotten, neglected, bumped, 16 | banged, broken, glued together,--anything and everything it suffered, 17 | until many a time it said sadly enough to its poor little self, "I 18 | might as well be a human being at once and be done with it!" And then 19 | it fell to thinking about human beings; what strange creatures they 20 | were, always going about, though none carried them save when they were 21 | very little; always sleeping and waking, and eating and drinking, and 22 | laughing and crying, and talking and walking, and doing this and that 23 | and the other, never resting for long together, or seeming as if they 24 | could be still for even a single day. "They are always making a noise," 25 | thought the wooden doll; "they are always talking and walking about, 26 | always moving things and doing things, building up and pulling down, 27 | and making and unmaking for ever and for ever, and never are they 28 | quiet. It is lucky that we are not all human beings, or the world would 29 | be worn out in no time, and there would not be a corner left in which 30 | to rest a poor doll's head." 31 | -------------------------------------------------------------------------------- /Section 2/code_2.1/outbox/The_Wooden_Doll.txt: -------------------------------------------------------------------------------- 1 | 2 | ".daeh s'llod roop a tser ot 3 | hcihw ni tfel renroc a eb ton dluow ereht dna ,emit on ni tuo nrow eb 4 | dluow dlrow eht ro ,sgnieb namuh lla ton era ew taht ykcul si tI .teiuq 5 | yeht era reven dna ,reve rof dna reve rof gnikamnu dna gnikam dna 6 | ,nwod gnillup dna pu gnidliub ,sgniht gniod dna sgniht gnivom syawla 7 | ,tuoba gniklaw dna gniklat syawla era yeht" ;llod nedoow eht thguoht 8 | ",esion a gnikam syawla era yehT" .yad elgnis a neve rof llits eb dluoc 9 | yeht fi sa gnimees ro ,rehtegot gnol rof gnitser reven ,rehto eht dna 10 | taht dna siht gniod dna ,gniklaw dna gniklat dna ,gniyrc dna gnihgual 11 | dna ,gniknird dna gnitae dna ,gnikaw dna gnipeels syawla ;elttil yrev 12 | erew yeht nehw evas meht deirrac enon hguoht ,tuoba gniog syawla ,erew 13 | yeht serutaerc egnarts tahw ;sgnieb namuh tuoba gnikniht ot llef ti 14 | neht dnA "!ti htiw enod eb dna ecno ta gnieb namuh a eb llew sa thgim 15 | I" ,fles elttil roop sti ot hguone yldas dias ti emit a ynam litnu 16 | ,dereffus ti gnihtyreve dna gnihtyna--,rehtegot deulg ,nekorb ,degnab 17 | ,depmub ,detcelgen ,nettogrof ,sriats no deppord ,srenroc ni tuoba tfel 18 | ,loohcs ot tnew yeht nehw slehctas rieht otni deffuts ,srehtaew lla ni 19 | tuo nekat ,desserd erew yeht nehw desserd ,dehtab erew yeht nehw dehtab 20 | eb ,pu tog yeht nehw pu teg ot ,deb ot tnew nerdlihc eht nehw deb 21 | ot og ot edam ,stnemom ddo fo srennam lla ta nwod tup dna pu nekat saw 22 | ti ;ecaep yna dah reven tI .saw ti tahw naht rehtar htrae no gnihtyna 23 | ro ,bmal ylloow a ro ,sreidlos fo xob a ro ,niart nit a erew ti dehsiw 24 | llod nedoow roop eht emit a ynaM .eb ot gniht das a deedni si taht 25 | rof ,stnioj elbavom dna daeh detniap a htiw llod nedoow gnorts doog 26 | a naht rehtar dlrow eht ni gnihtyna--kaerb ot ysae llod anihc a ro ,tuo 27 | ezoo ot tpa tsudwas fo lluf llod a ro ,llod xaw a ro ,llod gar a eb 28 | ot epoh ,llod a era uoy reve fi ,sraed yM .ecaep on dah llod nedoow ehT 29 | 30 | 31 | .LLOD NEDOOW EHT -------------------------------------------------------------------------------- /Section 2/code_2.2/inbox/The_Wooden_Doll.txt: -------------------------------------------------------------------------------- 1 | THE WOODEN DOLL. 2 | 3 | 4 | The wooden doll had no peace. My dears, if ever you are a doll, hope to 5 | be a rag doll, or a wax doll, or a doll full of sawdust apt to ooze 6 | out, or a china doll easy to break--anything in the world rather than a 7 | good strong wooden doll with a painted head and movable joints, for 8 | that is indeed a sad thing to be. Many a time the poor wooden doll 9 | wished it were a tin train, or a box of soldiers, or a woolly lamb, or 10 | anything on earth rather than what it was. It never had any peace; it 11 | was taken up and put down at all manners of odd moments, made to go to 12 | bed when the children went to bed, to get up when they got up, be 13 | bathed when they were bathed, dressed when they were dressed, taken out 14 | in all weathers, stuffed into their satchels when they went to school, 15 | left about in corners, dropped on stairs, forgotten, neglected, bumped, 16 | banged, broken, glued together,--anything and everything it suffered, 17 | until many a time it said sadly enough to its poor little self, "I 18 | might as well be a human being at once and be done with it!" And then 19 | it fell to thinking about human beings; what strange creatures they 20 | were, always going about, though none carried them save when they were 21 | very little; always sleeping and waking, and eating and drinking, and 22 | laughing and crying, and talking and walking, and doing this and that 23 | and the other, never resting for long together, or seeming as if they 24 | could be still for even a single day. "They are always making a noise," 25 | thought the wooden doll; "they are always talking and walking about, 26 | always moving things and doing things, building up and pulling down, 27 | and making and unmaking for ever and for ever, and never are they 28 | quiet. It is lucky that we are not all human beings, or the world would 29 | be worn out in no time, and there would not be a corner left in which 30 | to rest a poor doll's head." 31 | -------------------------------------------------------------------------------- /Section 2/code_2.2/outbox/The_Wooden_Doll.txt: -------------------------------------------------------------------------------- 1 | 2 | ".daeh s'llod roop a tser ot 3 | hcihw ni tfel renroc a eb ton dluow ereht dna ,emit on ni tuo nrow eb 4 | dluow dlrow eht ro ,sgnieb namuh lla ton era ew taht ykcul si tI .teiuq 5 | yeht era reven dna ,reve rof dna reve rof gnikamnu dna gnikam dna 6 | ,nwod gnillup dna pu gnidliub ,sgniht gniod dna sgniht gnivom syawla 7 | ,tuoba gniklaw dna gniklat syawla era yeht" ;llod nedoow eht thguoht 8 | ",esion a gnikam syawla era yehT" .yad elgnis a neve rof llits eb dluoc 9 | yeht fi sa gnimees ro ,rehtegot gnol rof gnitser reven ,rehto eht dna 10 | taht dna siht gniod dna ,gniklaw dna gniklat dna ,gniyrc dna gnihgual 11 | dna ,gniknird dna gnitae dna ,gnikaw dna gnipeels syawla ;elttil yrev 12 | erew yeht nehw evas meht deirrac enon hguoht ,tuoba gniog syawla ,erew 13 | yeht serutaerc egnarts tahw ;sgnieb namuh tuoba gnikniht ot llef ti 14 | neht dnA "!ti htiw enod eb dna ecno ta gnieb namuh a eb llew sa thgim 15 | I" ,fles elttil roop sti ot hguone yldas dias ti emit a ynam litnu 16 | ,dereffus ti gnihtyreve dna gnihtyna--,rehtegot deulg ,nekorb ,degnab 17 | ,depmub ,detcelgen ,nettogrof ,sriats no deppord ,srenroc ni tuoba tfel 18 | ,loohcs ot tnew yeht nehw slehctas rieht otni deffuts ,srehtaew lla ni 19 | tuo nekat ,desserd erew yeht nehw desserd ,dehtab erew yeht nehw dehtab 20 | eb ,pu tog yeht nehw pu teg ot ,deb ot tnew nerdlihc eht nehw deb 21 | ot og ot edam ,stnemom ddo fo srennam lla ta nwod tup dna pu nekat saw 22 | ti ;ecaep yna dah reven tI .saw ti tahw naht rehtar htrae no gnihtyna 23 | ro ,bmal ylloow a ro ,sreidlos fo xob a ro ,niart nit a erew ti dehsiw 24 | llod nedoow roop eht emit a ynaM .eb ot gniht das a deedni si taht 25 | rof ,stnioj elbavom dna daeh detniap a htiw llod nedoow gnorts doog 26 | a naht rehtar dlrow eht ni gnihtyna--kaerb ot ysae llod anihc a ro ,tuo 27 | ezoo ot tpa tsudwas fo lluf llod a ro ,llod xaw a ro ,llod gar a eb 28 | ot epoh ,llod a era uoy reve fi ,sraed yM .ecaep on dah llod nedoow ehT 29 | 30 | 31 | .LLOD NEDOOW EHT -------------------------------------------------------------------------------- /Section 2/code_2.3/inbox/The_Wooden_Doll.txt: -------------------------------------------------------------------------------- 1 | THE WOODEN DOLL. 2 | 3 | 4 | The wooden doll had no peace. My dears, if ever you are a doll, hope to 5 | be a rag doll, or a wax doll, or a doll full of sawdust apt to ooze 6 | out, or a china doll easy to break--anything in the world rather than a 7 | good strong wooden doll with a painted head and movable joints, for 8 | that is indeed a sad thing to be. Many a time the poor wooden doll 9 | wished it were a tin train, or a box of soldiers, or a woolly lamb, or 10 | anything on earth rather than what it was. It never had any peace; it 11 | was taken up and put down at all manners of odd moments, made to go to 12 | bed when the children went to bed, to get up when they got up, be 13 | bathed when they were bathed, dressed when they were dressed, taken out 14 | in all weathers, stuffed into their satchels when they went to school, 15 | left about in corners, dropped on stairs, forgotten, neglected, bumped, 16 | banged, broken, glued together,--anything and everything it suffered, 17 | until many a time it said sadly enough to its poor little self, "I 18 | might as well be a human being at once and be done with it!" And then 19 | it fell to thinking about human beings; what strange creatures they 20 | were, always going about, though none carried them save when they were 21 | very little; always sleeping and waking, and eating and drinking, and 22 | laughing and crying, and talking and walking, and doing this and that 23 | and the other, never resting for long together, or seeming as if they 24 | could be still for even a single day. "They are always making a noise," 25 | thought the wooden doll; "they are always talking and walking about, 26 | always moving things and doing things, building up and pulling down, 27 | and making and unmaking for ever and for ever, and never are they 28 | quiet. It is lucky that we are not all human beings, or the world would 29 | be worn out in no time, and there would not be a corner left in which 30 | to rest a poor doll's head." 31 | -------------------------------------------------------------------------------- /Section 2/code_2.3/outbox/The_Wooden_Doll.txt: -------------------------------------------------------------------------------- 1 | 2 | ".daeh s'llod roop a tser ot 3 | hcihw ni tfel renroc a eb ton dluow ereht dna ,emit on ni tuo nrow eb 4 | dluow dlrow eht ro ,sgnieb namuh lla ton era ew taht ykcul si tI .teiuq 5 | yeht era reven dna ,reve rof dna reve rof gnikamnu dna gnikam dna 6 | ,nwod gnillup dna pu gnidliub ,sgniht gniod dna sgniht gnivom syawla 7 | ,tuoba gniklaw dna gniklat syawla era yeht" ;llod nedoow eht thguoht 8 | ",esion a gnikam syawla era yehT" .yad elgnis a neve rof llits eb dluoc 9 | yeht fi sa gnimees ro ,rehtegot gnol rof gnitser reven ,rehto eht dna 10 | taht dna siht gniod dna ,gniklaw dna gniklat dna ,gniyrc dna gnihgual 11 | dna ,gniknird dna gnitae dna ,gnikaw dna gnipeels syawla ;elttil yrev 12 | erew yeht nehw evas meht deirrac enon hguoht ,tuoba gniog syawla ,erew 13 | yeht serutaerc egnarts tahw ;sgnieb namuh tuoba gnikniht ot llef ti 14 | neht dnA "!ti htiw enod eb dna ecno ta gnieb namuh a eb llew sa thgim 15 | I" ,fles elttil roop sti ot hguone yldas dias ti emit a ynam litnu 16 | ,dereffus ti gnihtyreve dna gnihtyna--,rehtegot deulg ,nekorb ,degnab 17 | ,depmub ,detcelgen ,nettogrof ,sriats no deppord ,srenroc ni tuoba tfel 18 | ,loohcs ot tnew yeht nehw slehctas rieht otni deffuts ,srehtaew lla ni 19 | tuo nekat ,desserd erew yeht nehw desserd ,dehtab erew yeht nehw dehtab 20 | eb ,pu tog yeht nehw pu teg ot ,deb ot tnew nerdlihc eht nehw deb 21 | ot og ot edam ,stnemom ddo fo srennam lla ta nwod tup dna pu nekat saw 22 | ti ;ecaep yna dah reven tI .saw ti tahw naht rehtar htrae no gnihtyna 23 | ro ,bmal ylloow a ro ,sreidlos fo xob a ro ,niart nit a erew ti dehsiw 24 | llod nedoow roop eht emit a ynaM .eb ot gniht das a deedni si taht 25 | rof ,stnioj elbavom dna daeh detniap a htiw llod nedoow gnorts doog 26 | a naht rehtar dlrow eht ni gnihtyna--kaerb ot ysae llod anihc a ro ,tuo 27 | ezoo ot tpa tsudwas fo lluf llod a ro ,llod xaw a ro ,llod gar a eb 28 | ot epoh ,llod a era uoy reve fi ,sraed yM .ecaep on dah llod nedoow ehT 29 | 30 | 31 | .LLOD NEDOOW EHT -------------------------------------------------------------------------------- /Section 2/code_2.4/async-generators/inbox/The_Wooden_Doll.txt: -------------------------------------------------------------------------------- 1 | THE WOODEN DOLL. 2 | 3 | 4 | The wooden doll had no peace. My dears, if ever you are a doll, hope to 5 | be a rag doll, or a wax doll, or a doll full of sawdust apt to ooze 6 | out, or a china doll easy to break--anything in the world rather than a 7 | good strong wooden doll with a painted head and movable joints, for 8 | that is indeed a sad thing to be. Many a time the poor wooden doll 9 | wished it were a tin train, or a box of soldiers, or a woolly lamb, or 10 | anything on earth rather than what it was. It never had any peace; it 11 | was taken up and put down at all manners of odd moments, made to go to 12 | bed when the children went to bed, to get up when they got up, be 13 | bathed when they were bathed, dressed when they were dressed, taken out 14 | in all weathers, stuffed into their satchels when they went to school, 15 | left about in corners, dropped on stairs, forgotten, neglected, bumped, 16 | banged, broken, glued together,--anything and everything it suffered, 17 | until many a time it said sadly enough to its poor little self, "I 18 | might as well be a human being at once and be done with it!" And then 19 | it fell to thinking about human beings; what strange creatures they 20 | were, always going about, though none carried them save when they were 21 | very little; always sleeping and waking, and eating and drinking, and 22 | laughing and crying, and talking and walking, and doing this and that 23 | and the other, never resting for long together, or seeming as if they 24 | could be still for even a single day. "They are always making a noise," 25 | thought the wooden doll; "they are always talking and walking about, 26 | always moving things and doing things, building up and pulling down, 27 | and making and unmaking for ever and for ever, and never are they 28 | quiet. It is lucky that we are not all human beings, or the world would 29 | be worn out in no time, and there would not be a corner left in which 30 | to rest a poor doll's head." 31 | -------------------------------------------------------------------------------- /Section 2/code_2.4/async-generators/outbox/The_Wooden_Doll.txt: -------------------------------------------------------------------------------- 1 | 2 | ".daeh s'llod roop a tser ot 3 | hcihw ni tfel renroc a eb ton dluow ereht dna ,emit on ni tuo nrow eb 4 | dluow dlrow eht ro ,sgnieb namuh lla ton era ew taht ykcul si tI .teiuq 5 | yeht era reven dna ,reve rof dna reve rof gnikamnu dna gnikam dna 6 | ,nwod gnillup dna pu gnidliub ,sgniht gniod dna sgniht gnivom syawla 7 | ,tuoba gniklaw dna gniklat syawla era yeht" ;llod nedoow eht thguoht 8 | ",esion a gnikam syawla era yehT" .yad elgnis a neve rof llits eb dluoc 9 | yeht fi sa gnimees ro ,rehtegot gnol rof gnitser reven ,rehto eht dna 10 | taht dna siht gniod dna ,gniklaw dna gniklat dna ,gniyrc dna gnihgual 11 | dna ,gniknird dna gnitae dna ,gnikaw dna gnipeels syawla ;elttil yrev 12 | erew yeht nehw evas meht deirrac enon hguoht ,tuoba gniog syawla ,erew 13 | yeht serutaerc egnarts tahw ;sgnieb namuh tuoba gnikniht ot llef ti 14 | neht dnA "!ti htiw enod eb dna ecno ta gnieb namuh a eb llew sa thgim 15 | I" ,fles elttil roop sti ot hguone yldas dias ti emit a ynam litnu 16 | ,dereffus ti gnihtyreve dna gnihtyna--,rehtegot deulg ,nekorb ,degnab 17 | ,depmub ,detcelgen ,nettogrof ,sriats no deppord ,srenroc ni tuoba tfel 18 | ,loohcs ot tnew yeht nehw slehctas rieht otni deffuts ,srehtaew lla ni 19 | tuo nekat ,desserd erew yeht nehw desserd ,dehtab erew yeht nehw dehtab 20 | eb ,pu tog yeht nehw pu teg ot ,deb ot tnew nerdlihc eht nehw deb 21 | ot og ot edam ,stnemom ddo fo srennam lla ta nwod tup dna pu nekat saw 22 | ti ;ecaep yna dah reven tI .saw ti tahw naht rehtar htrae no gnihtyna 23 | ro ,bmal ylloow a ro ,sreidlos fo xob a ro ,niart nit a erew ti dehsiw 24 | llod nedoow roop eht emit a ynaM .eb ot gniht das a deedni si taht 25 | rof ,stnioj elbavom dna daeh detniap a htiw llod nedoow gnorts doog 26 | a naht rehtar dlrow eht ni gnihtyna--kaerb ot ysae llod anihc a ro ,tuo 27 | ezoo ot tpa tsudwas fo lluf llod a ro ,llod xaw a ro ,llod gar a eb 28 | ot epoh ,llod a era uoy reve fi ,sraed yM .ecaep on dah llod nedoow ehT 29 | 30 | 31 | .LLOD NEDOOW EHT -------------------------------------------------------------------------------- /Section 4/code_4.3/Class/dist/app.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["CurrencyConverter.js","app.js"],"names":["CurrencyConverter","base","to","target","name","descriptor","fn","value","args","result","call","currencyRate","toUpperCase","data","error","console","log","Cost","compute","qty","price","Promise","resolve","then"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;AAEA,MAAMA,iBAAiB,GAAG,CAACC,IAAD,EAAOC,EAAP,KAAc;AACtC,SAAO,UAAUC,MAAV,EAAkBC,IAAlB,EAAwBC,UAAxB,EAAoC;AACzC,QAAI;AACF,YAAMC,EAAE,GAAGD,UAAU,CAACE,KAAtB,CADE,CAC2B;;AAC7BF,MAAAA,UAAU,CAACE,KAAX,GAAmB,OAAO,GAAGC,IAAV,KAAmB;AACpC;AACA,cAAMC,MAAM,GAAG,MAAMH,EAAE,CAACI,IAAH,CAAQ,IAAR,EAAc,GAAGF,IAAjB,CAArB;AACA,cAAMG,YAAY,GAAG,MAAM,oBAAO,0DAAyDT,EAAE,CAACU,WAAH,EAAiB,IAAGX,IAAI,CAACW,WAAL,EAAmB,YAAvG,CAA3B;AAEA,eAAO,OAAOD,YAAY,CAACE,IAAb,CAAmB,GAAEX,EAAE,CAACU,WAAH,EAAiB,IAAGX,IAAI,CAACW,WAAL,EAAmB,EAA5D,EAA+D,KAA/D,IAAwEH,MAA/E,CAAP;AACD,OAND;;AAQA,aAAOJ,UAAP;AACD,KAXD,CAWE,OAAOS,KAAP,EAAc;AACdC,MAAAA,OAAO,CAACC,GAAR,CAAYF,KAAZ;AACD;AACF,GAfD;AAgBD,CAjBD;;eAmBed;;;;;;;ACrBf;;;;;;IAEMiB,eACH,gCAAkB,KAAlB,EAAyB,KAAzB,aADH,MAAMA,IAAN,CAAW;AAETC,EAAAA,OADA,CACQC,GADR,EACaC,KADb,EACoB;AAClB,WAAOC,OAAO,CAACC,OAAR,CAAgBH,GAAG,GAAGC,KAAtB,CAAP;AACD;;AAJQ;AAOX,MAAMA,KAAK,GAAG,IAAIH,IAAJ,EAAd;AACAG,KAAK,CAACF,OAAN,CAAc,EAAd,EAAkB,CAAlB,EAAqBK,IAArB,CAA0Bd,MAAM,IAAIM,OAAO,CAACC,GAAR,CAAYP,MAAZ,CAApC","file":"app.map","sourceRoot":"..","sourcesContent":["import axios from \"axios\";\n\nconst CurrencyConverter = (base, to) => {\n return function (target, name, descriptor) {\n try {\n const fn = descriptor.value; // The original function\n descriptor.value = async (...args) => {\n // Define the decorator\n const result = await fn.call(this, ...args);\n const currencyRate = await axios(`https://free.currencyconverterapi.com/api/v6/convert?q=${to.toUpperCase()}_${base.toUpperCase()}&compact=y`);\n\n return await (currencyRate.data[`${to.toUpperCase()}_${base.toUpperCase()}`][\"val\"] * result);\n }\n\n return descriptor;\n } catch (error) {\n console.log(error);\n }\n }\n}\n\nexport default CurrencyConverter;","import CurrencyConverter from \"./CurrencyConverter\";\n\nclass Cost {\n @CurrencyConverter(\"INR\", \"USD\")\n compute(qty, price) {\n return Promise.resolve(qty * price);\n }\n}\n\nconst price = new Cost();\nprice.compute(20, 5).then(result => console.log(result));"]} -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Node.js Design Patterns [Video] 5 | This is the code repository for [Node.js Design Patterns [Video]](https://www.packtpub.com/web-development/nodejs-design-patterns-video?utm_source=github&utm_medium=repository&utm_campaign=9781789538397), published by [Packt](https://www.packtpub.com/?utm_source=github). It contains all the supporting project files necessary to work through the video course from start to finish. 6 | ## About the Video Course 7 | When writing Node.js applications, it’s absolutely imperative that we employ battle-tested guidelines that can help us write efficient and resilient code. These guidelines are known as design patterns. Design patterns are an important part of software development and are a proven way of solving a given problem. 8 | 9 | In this course, you’ll take a comprehensive look at industry-standard design patterns, identify challenges that you would commonly encounter while designing and developing software, and implement solutions in Node.js applications. The efficacy of these patterns has been proven over time and a lot of these standard patterns can be implemented when writing JavaScript apps with Node.js. 10 | 11 | By implementing design patterns, you can write code that is crafted for efficiency and reusability and is resilient against errors and typical pitfalls that result from poorly written code. 12 | 13 |