Last active
July 26, 2017 11:07
-
-
Save vgvinay2/3521a3d1854c13c3157df7cd80957bad to your computer and use it in GitHub Desktop.
Modularizing Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Question1 Write program to implement Doubly Linked List -> use module pattern and import in other file to perform operation | |
//doubly-linked_list.js | |
function Node(value) { | |
this.data = value; | |
this.previous = null; | |
this.next = null; | |
} | |
function DoublyList() { | |
this._length = 0; | |
this.head = null; | |
this.tail = null; | |
} | |
DoublyList.prototype.add = function(value) { | |
var node = new Node(value); | |
if (this._length) { | |
this.tail.next = node; | |
node.previous = this.tail; | |
this.tail = node; | |
} else { | |
this.head = node; | |
this.tail = node; | |
} | |
this._length++; | |
return node; | |
}; | |
export default DoublyList | |
//add_module.js | |
import add from './doubly-linked_list.js' | |
doublylist = new DoublyList | |
doublylist.add(1); | |
doublylist.add(2); | |
doublylist.add(3); | |
console.log(doublylist); | |
Question2 Write matrix program to find sum of elements using module pattern. | |
Solution | |
//Matrix_module.js | |
function get_sum(arr) { | |
var sum = 0; | |
arr.forEach(function(v) { | |
if (typeof v == 'object') | |
sum += MatrixSum(v); | |
else | |
sum += v | |
}) | |
return sum; | |
} | |
export default get_sum | |
//consume_module.js | |
import get_sum from './MatrixModule.js' | |
sum = get_sum([[1, 2, 3], [1, 2, 3], [1, 2, 3]]); | |
console.log(sum); | |
Question3 Get data from rest api using npm modules. | |
Solution | |
const request = require('request'); | |
const util = require('util'); | |
function getUserInfo(username) { | |
request({ | |
url: `https://api.stackexchange.com/2.2/tags/ruby/related?site=stackoverflow`, | |
method: 'GET' | |
}, function (err, response, body) { | |
if (err) { | |
console.error(err); | |
}else{ | |
console.log(util.inspect(body, false, null)) | |
} | |
}); | |
}; | |
Question4 Write a program to catch exceptions with your own examples. | |
Solution | |
let num = 1; | |
try { | |
num.toPrecision(500); | |
} | |
catch(err) { | |
console.log(err.name); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment