diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40b878d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules/ \ No newline at end of file diff --git a/README.md b/README.md index c32c34d..5c4d900 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,8 @@ # assignment_async_nodejs Async Node.js sprint + +

Maddie Rajavasireddy

+ +Run code using command `node index.js` + +Index.js contains solutions for the Warmups and test code for the File Operations and Event Emitter diff --git a/data/lorem.txt b/data/lorem.txt new file mode 100644 index 0000000..5f5e1e0 --- /dev/null +++ b/data/lorem.txt @@ -0,0 +1,6 @@ +Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod +tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, +quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo +consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse +cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non +proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \ No newline at end of file diff --git a/data/test.txt b/data/test.txt new file mode 100644 index 0000000..b861aad --- /dev/null +++ b/data/test.txt @@ -0,0 +1 @@ +Hello!Hello again! \ No newline at end of file diff --git a/emitter.js b/emitter.js new file mode 100644 index 0000000..f9ae615 --- /dev/null +++ b/emitter.js @@ -0,0 +1,74 @@ +'use strict'; + +const Emitter = function() { + + // store for events and their listeners + this.events = {}; + + + // attach a listener for a particular event + this.on = function(eventType, callback) { + + // add an event if not there + if (this.events[eventType] === undefined) { + this.events[eventType] = []; + } + + // then attach listeners + this.events[eventType].push(callback); + + }; + + // invoke all listeners for a particular event + this.emit = function(eventType) { + + let callbacks = this.events[eventType]; + + // check if any listeners for this event + if (callbacks !== undefined) { + + // loop though all listeners for this event + callbacks.forEach(function(callback) { + callback(); + }); + } else { + + // output error message if no listeners exist for given event + console.log("this event type does not exist"); + } + + }; + + // remove a particular listener of given events + this.removeListener = function(eventType, callback) { + + // check if any listeners for this event + let callbacks = this.events[eventType]; + + if (callbacks !== undefined) { + + //get index of listener to remove + let callbackIndex = callbacks.indexOf(callback); + + if (callbackIndex >= 0) { + + // remove that listener + callbacks.splice(callbackIndex, 1); + } + + } + + }; + + // remove all listeners from a particular event + this.removeAllListeners = function(eventType) { + + //delete all listeners on given event in one go + delete this.events[eventType]; + + }; + +} + + +module.exports = Emitter; \ No newline at end of file diff --git a/fsp.js b/fsp.js new file mode 100644 index 0000000..e41c72e --- /dev/null +++ b/fsp.js @@ -0,0 +1,41 @@ +'use strict'; + +const fs = require("fs"); +let path = "./data/lorem.txt"; + +let fsp = { + readFile: function(path) { + return new Promise((resolve, reject) => { + fs.readFile(path, 'utf8', (error, data) => { + if(error) { + reject(error); + } + resolve(data); + }); + }); + }, + + writeFile: function(file, data) { + return new Promise((resolve, reject) => { + fs.writeFile(file, data, (error) => { + if(error) { + reject(error); + } + resolve(data); + }); + }); + }, + + appendFile: function(file, data) { + return new Promise((resolve, reject) => { + fs.appendFile(file, data, (error) => { + if(error) { + reject(error); + } + resolve(data); + }); + }); + }, +}; + +module.exports = fsp; \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..ca2f2ac --- /dev/null +++ b/index.js @@ -0,0 +1,202 @@ +'use strict'; + +const fsp = require("./fsp"); +const Emitter = require("./emitter"); //"events"); -- works just the same after switch out + + +// 1. Create a promise that resolves the message "Hello Promise!" after 1 sec +let p = Promise.resolve("Hello Promise!"); + +p.then(function(message) { + + setTimeout(function () { + console.log(message); + }, 1000); + +}); + + +// 2. Create a function with the following signature: delay(milliseconds) +function delay (time) { + return new Promise(resolve => setTimeout(resolve(time), time)); +} + +function countDown(num) { + + if(num > 0) { + console.log(num); + num -= 100; + } else { + console.log('Done!'); + } + + return num; +} + +delay(1000) + .then(countDown) //=> 1000 + .then(countDown) //=> 900 + .then(countDown) //=> 800 + .then(countDown) //=> 700 + .then(countDown) //=> 600 + .then(countDown) //=> 500 + .then(countDown) //=> 400 + .then(countDown) //=> 300 + .then(countDown) //=> 200 + .then(countDown) //=> 100 + .then(countDown); //=> Done! + + + +// 3. Create a function that accepts a number and returns a promise +// that resolves that number squared +function square(integer) { + return new Promise( function(resolve, reject) { + + if(Number.isInteger(integer)) { + resolve(integer * integer); + } else { + reject(); + } + + }); +} + +let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]; +nums = nums.map(i => square(i)); + +Promise.all(nums) + .then(results => console.log(results)); + + + +// 4. Create a function with this signature doBadThing(forRealz) +function doBadThing(forRealz) { + return new Promise( function(resolve, reject){ + if (forRealz == false) { + resolve("Yay!"); + } else { + reject("Nay!"); + } + }); +} + +doBadThing(true).then(function(result) { + console.log(result); +}, function(err) { //reject handler + console.error("reject message: " + err); + } +); + +doBadThing(false) + .then(function(result) { + console.log(result); + throw "Trigger the catch!"; //throw error + }) + .catch(function(err) { //catch error + console.error("catch message: " + err); + }); + + + +// File Operations using Promises +// readFile, writeFile, appendFile + +fsp.readFile("./data/lorem.txt") + .then(function(data) { + // Outputs the file data + console.log(data); + }) + .catch(function(err) { + console.error(err); + } +); + +fsp.writeFile("./data/test.txt", "Hello!") + .then(function(res) { + // Outputs the file data + // after writing + console.log(res); + }) + .catch(function(err) { + console.error(err); + } +); + +fsp.appendFile("./data/test.txt", 'Hello again!') + .then(function(res) { + // Outputs the file data + // after appending + console.log(res); + }) + .catch(function(err) { + console.error(err); + } +); + + + +// Event Emitter +// Create an event emitter similar to the NodeJS EventEmitter but a smaller version +// Should be able to: +// a. attach an event listener with `.on(eventType, callback)` +// b. invoke all listeners attached to a particular event with `.emit(eventType)` +// c. remove a particular listener from the given event with `.removeListener(eventType, callback)` +// d. remove all listeners from the given event with `.removeAllListeners(eventType)` + +// Set up Emitter +let emitter = new Emitter(); + +const callback1 = function(){ + console.log("Click 1"); +}; + +// Attach an event listener on click event +emitter.on("click", callback1); + +// Attach another listener on click event +emitter.on("click", function(){ + console.log("Click 2"); +}); + +// Attach another listener on click event +emitter.on("click", function(){ + console.log("Click 3"); +}); + +// Attach a listener on change event +emitter.on("change", function(){ + console.log("Change 1"); +}); + +// Attach another listener on change event +emitter.on("change", function(){ + console.log("Change 2"); +}); + + +// Emit a click event - should result in all listeners attached to click event being invoked +console.log("Print out all listeners on click event"); +emitter.emit("click"); + +// Emit a change event - should result in all listeners attached to change event being invoked +console.log("Print out all listeners on change event"); +emitter.emit("change"); + +console.log("Remove Click 1 listener on click event"); +emitter.removeListener("click", callback1); + +// Emit a click event - should result in all listeners attached to click event being invoked +console.log("Print out all listeners on click event - should have Click 2 and Click 3"); +emitter.emit("click"); + +// Remove all listeners on an event with emitter.removeAllListeners(eventType) +console.log("Remove all listeners on click event"); +emitter.removeAllListeners("click"); + +// Emit a click event - should result in all listeners attached to click event being invoked +console.log("Print out all listeners on click event - should not have any left"); +emitter.emit("click"); + + + diff --git a/package.json b/package.json new file mode 100644 index 0000000..3cdae07 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "assignment_async_nodejs", + "version": "1.0.0", + "description": "Async Node.js sprint", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/maddiereddy/assignment_async_nodejs.git" + }, + "author": "Maddie Rajavasireddy", + "license": "ISC", + "bugs": { + "url": "https://github.com/maddiereddy/assignment_async_nodejs/issues" + }, + "homepage": "https://github.com/maddiereddy/assignment_async_nodejs#readme" +}