Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Hackerrank Nodejs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19
At a glance
Powered by AI
Some key concepts covered in the document include working with timers, finding sums and factors of numbers, Fibonacci series, palindromes, prime numbers, file handling using streams in Node.js.

You can use setInterval() to execute a function periodically or use setTimeout() to execute a function once after a delay. Using clearInterval() allows you to stop an interval from executing.

You can use a for loop to iterate from 0 to the given number, check if each number is divisible by 3 or 5 using the modulo operator, and add it to the running sum if it is divisible.

1. add two number and print the result in nodejs use process.

argv

var sum = 0;
for (i = 2; i < process.argv.length; i++) {
sum += Number(process.argv[i]);
}

console.log(sum);
2. TIMER 1

setInterval(function() {
console.log("TCS");
}, 5000);
3. TIMER 2

setTimeout(function() {
console.log("TCS");
}, 2000);

Working with Timers#3

let TCS = 'The actors are here!';

// However, the cue is not announced until at least 5000ms have


// passed through the use of setTimeout
var interval = setInterval(function(){
console.log(TCS);
}, 2000);
setTimeout(function() {
clearInterval(interval);
}, 10000);
// This console log is executed right away
console.log('TCS');
4. Find the sum of all multiples of 3 and 5 below 1000 node js

var sum = 0;
for (var x = 0; x < 1000; x++)
{
if (x % 3 === 0 || x % 5 === 0)
{
sum += x;
}
}
console.log(sum);
5. Create a Node.js app which contains two modules; one named App and
the other named modules, which adds and multiplies two given numbers
as input. Use readline core module for i/o

const readline = require('readline').createInterface({


input: process.stdin,
output: process.stdout
})

readline.question(`Enter first number?`, (fnum) => {


console.log(`${fnum}`)
readline.close()
})
readline.question(`Enter second number?`, (snum) => {
console.log(`${snum}`)
readline.close()
})

Fibonacci Series
function solution()
{
var fibno = [ 1, 2 ], sum = 0;

function cal(arr )
{
return arr[ arr.length - 1 ] + arr[ arr.length - 2 ];
}

while ( fibno[ fibno.length - 1 ] < 4e+6 )


{
fibno.push( cal(fibno) );
}

fibno.forEach( function(n)
{
if ( n % 2 === 0 )
{
sum += n;
}
});
return sum;
}

console.log(solution())

Largest Prime Factor

var divisor = 2;
var number = 600851475143;
while(number > 1){
if(number % divisor === 0){
number /= divisor;
} else {
divisor++;
}
}
console.log(divisor); //the largest prime factor of 600851475143

Palindrome
function largestPalindrome(){

var arr = [];


for(var i =999; i>100; i--){
for(var j = 999; j>100; j--){
var mul = j*i;
if(isPalin(mul)){
arr.push(j * i);
}
}
}

return Math.max.apply(Math, arr);


}

function isPalin(i){
return i.toString() == i.toString().split("").reverse().join("");
}

console.log(largestPalindrome());

Evenly Divisible Number


2520 is the smallest number that can be divided by each of the numbers from 1 to 10
without any remainder. What is the smallest positive number that is evenly divisible by
all of the numbers from 1 to 20?

function smallestDivisible(limit) {
var i, n = 1;

function largestPower(n, limit) {


var p, e = 2, largest = n;
while ((p = Math.pow(n, e)) <= limit) {
largest = p;
e += 1;
}
return largest;
}

function isPrime(n) {
var i, limit = Math.ceil(Math.sqrt(n));
// since the main loop generates odd numbers only
//we can start testing primality dividing by 3
for (i = 3; i <= limit; i += 2) {
if (n % i === 0) {
return false;
}
}
return true;
}
for (i = 3; i <= limit; i += 2) {
if (isPrime(i)) {
n *= largestPower(i, limit);
}
}

return n * largestPower(2, limit);


}

console.log(smallestDivisible(20));

Sum of Squares
Find difference between sum of squares of the first 100 natural numbers
and square of the sum:

var squareOfSum = 0
var sumOfSquare = 0
var difference = 0

for (var i = 1; i < 101; i++) {


squareOfSum += i
sumOfSquare += i * i
}

squareOfSum = squareOfSum * squareOfSum


difference = squareOfSum - sumOfSquare
console.log(difference)

nth Prime Position


function primeMover(n){
var primes = [2];
var x = 3;
var count = 0;
do{
for(var y=2; y<x; y++){
if(x%y===0){
count++;
}
}
if(count===0){
primes.push(x);
x++;
}else{
x++;
count=0;
}
}
while(primes.length<n);
return primes[primes.length-1];
}

console.log(primeMover(10001));

Pythogorean Triplet:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product
abc.

for(var a = 1; a < 500; a++){


for(var b = a; b < 1000; b++){
var c = Math.sqrt(a * a + b * b);
if(c > b && Number.isInteger(c) && a + b + c == 1000){
console.log(a * b * c);
}
}
}

Sum of Primes
Find the sum of prime numbers below 2 million.

//Findthesumofprimenumbersbelow2million.
function sumPrimes(num) {
const primes = [];
const filteredArr = [];
let i;
let j;
for (i = 2; i <= num; i++) {
if (!filteredArr[i]) {
primes.push(i);

for (j = i * 2; j <= num; j += i) {


filteredArr[j] = true;
}
}
}
return primes.reduce((a, b) => a + b);
}
console.log(sumPrimes(2000000));

Sum of Multiples
Find the sum of all multiples of 3 and 5 below 1000 node js:

var sum = 0;
for (var x = 0; x < 1000; x++)
{
if (x % 3 === 0 || x % 5 === 0)
{
sum += x;
}
}
console.log(sum);

Events - file systems


var fs = require('fs')

const dir = dirname__ + 'Node_folder'

try {
if (!fs.existsSync(dir)){
fs.mkdirSync(dir)
}
} catch (err) {
console.error(err)
}
fs.writeFile('Node_folder/sample.txt', 'Learn Node FS
module', function (err) {
if (err) throw err;
console.log('File is created successfully.');
});

Events - http module -1

var http = require('http');


var server = http.createServer(function (request, response) {

//respond
response.write('Hello World');
response.end();
});
server.listen(8000);

Events - http module -2


var http = require('http');
//createaserverobject
http.createServer(function (req, res) {
res.read('./Sample.html');
res.end();
}).listen(8000);
console.log('Serverrunningat8000');

<DOCTYPE html>
<html>
<body>
<h2>
Welcome!whatwouldyouliketohave
</h2>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</body>

</html>

Events - Working with Custom Events


var events = require('events');
var eventEmitter = new events.EventEmitter();

//Create an event handler:


var MyEvent = function () {
console.log('HITHERE !HAPPYLEARNING');
}

//Assign the eventhandler to an event:


eventEmitter.on('Myfunc', MyEvent);

//Fire the event:


eventEmitter.emit('Myfunc');

Events - Working with files

var fs = require('fs');

fs.writeFileSync('To_Read.txt','This is Node.js a powerful backend


javascript used very widely in industry for developing web
applications.',function(err, data){
if (err) throw err;
});

fs.readFile('To_Read.txt', function(err, data) {


if (err) throw err;
console.log(data.toString('utf8'))
});

var fs = require("fs");

var readStream = fs.createReadStream("Node-stream-


handson/data_file.txt");

readStream.on("data", function(data) {

var chunk = data.toString();

const fileSizeInBytes = chunk.length;

const fileSizeInMegabytes = fileSizeInBytes / 1000000.0;

console.log(fileSizeInMegabytes);

});

var fs = require("fs");
var data = 'Node.js is an ultimate backend javascript for backend
developement ';
var writeStream = fs.createWriteStream('./Big_data.txt');

Explore Modules
var module=require('./module.js');
const readline = require('readline');

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

const r2 = readline.createInterface({
input: process.stdin,
output: process.stdout
});

rl.question('Please enter the first number', (answer1) => {


r2.question('Please enter the second number', (answer2) => {
var sum = module.AddNumber(answer1, answer2)
var product = module.MulNumber(answer1, answer2)

console.log(`The sum of above two numbers is ${result}`);


});
rl.close();
});

var exports=module.exports={};
exports.AddNumber=function(a,b)
{
return a+b;
};
exports.MulNumber=function(a,b)
{
return a*b;
};

exports.add = function (a, b) {


return a+b;
};

// Returns difference of two numbers


exports.subtract = function (a, b) {
return a-b;
};

// Returns product of two numbers


exports.multiply = function (a, b) {
return a*b;
};

App build – Routing 1


var http = require('http');

var server = http.createServer(function (req, res) {


if(req.url == "/hi"){
res.writeHead(200);
res.write('Hi Welcome');
}
else if(req.url == "/hello"){
res.writeHead(200);
res.write('Hello Buddy');
}
else{
res.writeHead(404);
res.write("404 Page not Found");
}
res.end();
});
server.listen(8000);

App build – Routing 2

var http = require('http');

var server = http.createServer(function (req, res) {


if(req.url == "/hi"){
res.writeHead(200);
res.write('Welcome Home');
}
else if(req.url == "/hello"){
res.writeHead(200);
res.write('HI TCSer');
}
else{
res.writeHead(404);
res.write("404 File not found error");
}
res.end();
});
server.listen(8000);

App build - Posting Data


var http = require('http');
var querystring = require('querystring');

var server = http.createServer(function (req, res) {


var url = req.url;
url = url.replace('?','');
url = url.replace('/','');
var query = querystring.parse(url);
console.log(query);
res.end();
});
server.listen(8000);

App build - Handling Requests


In terminal:

touch handlers.js

touch routers.js

touch server.js

App build - Server Setup


Write a snippet to set up a server in port 8000, and send a response
string " Hello World!"

var http = require('http');


var requestListener = function(req,res){
res.writeHead(200);
res.end('Hello World!');

var server = http.createServer(requestListener);


server.listen(3000,function(){
console.log("Listening on port 8000")
});

App build - Routing

const https = require('https');


var fs = require(“fs”);
const options = {
hostname: 'en.wikipedia.org',
port: 443,
path: '/wiki/Nodejs',
method: 'GET'
}

const req = https.request(options, (res) => {

res.on('data', (data) => {


fs.writeFile('Nodejs.html', data, function (err) {
if (err) throw err;

});

});
});
req.end();

const https = require('https')


const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'GET'
}

const req = https.request(options, (res) => {


console.log(`statusCode: ${res.statusCode}`)

res.on('data', (d) => fs.writeFile('helloworld.txt', 'Hello World!',


function (err) {
if (err) return console.log(err);
console.log('Hello World > helloworld.txt');
});

})

req.on('error', (error) => {


console.error(error)
})

req.end()
var handler = require('./Handler.js');
var http = require('http');
var requestListener = handler.handleRequest();

var server = http.createServer(requestListener);


server.listen(8000,function(){
console.log("Listening on port 8000")
});

const url = require('url');


module.exports = {
handleRequest(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});

let path = url.parse(request.url).pathname;

switch (path) {
case '/hi':
response.send('Hi Welcome');
break;
case '/hello':
response.send('Hello Buddy');
break;
default:
response.writeHead(404);
response.write('404 File not found');
response.end();
}
}
}
function smallestDivisible(limit) {

var i, n = 1;

function largestPower(n, limit) {

var p, e = 2, largest = n;

while ((p = Math.pow(n, e)) <= limit) {

largest = p;

e += 1;

return largest;

function isPrime(n) {

var i, limit = Math.ceil(Math.sqrt(n));

// since the main loop generates odd numbers only

// we can start testing primality dividing by 3

for (i = 3; i <= limit; i += 2) {

if (n % i === 0) {

return false;

return true;
}

for (i = 3; i <= limit; i += 2) {

if (isPrime(i)) {

n *= largestPower(i, limit);

return n * largestPower(2, limit);

console.log(smallestDivisible(20));

var fs = require("fs");
var stream = fs.createReadStream('Node-stream-
handson/data_file.txt','utf8',{ highWaterMark: 60000 });
var data = ''
var dataLength = 0;
//usingareadStreamthatwecreatedalready
stream
.on('data', function (chunk) {
dataLength += chunk.length;
data+=chunk;
})
.on('end', function () { //done
console.log(data);
console.log('Thelengthwas:', dataLength);
});

var fs = require("fs");
var stream = fs.createReadStream('Node-stream-
handson/data_file.txt','utf8',{ highWaterMark: 60000 });

stream .on("data", function(data) {


var chunk = data.toString();
console.log(chunk.length);
});

var fs = require("fs");

var readable = fs.createReadStream(__dirname + "/data_file.txt",


{encoding: 'utf8', highwater});

var writable = fs.createWriteStream(__dirname + "/new_data_file.txt");

readable.pipe(writable);

You might also like