Gurukula

fastify.get('/async-block-event-loop', async (_request, reply) => {
  const hash = crypto.createHash('sha256');
  const numberOfHasUpdates = 10e6;

  const updatehashAsync = async () => {
    hash.update(randomString());
  };

  for (let iter = 0; iter < numberOfHasUpdates; iter++) {
    await updatehashAsync();
  }
  reply.send({ data: 'Finished long process' });
});
fastify.get('/unblock-event-loop', async (_request, reply) => {
  const hash = crypto.createHash('sha256');
  const numberOfHasUpdates = 10e6;

  const breathSpace = async delayInS =>
    new Promise(res => setTimeout(() => res(), delayInS * 1000));

  for (let iter = 0; iter < numberOfHasUpdates; iter++) {
    await hash.update(getRandomString());
    await breathSpace(0);
  }
  reply.send({ data: 'Finished long process' });
});
function logA() { console.log('A') };
function logB() { console.log('B') };
function logC() { console.log('C') };
function logD() { console.log('D') };
function logE() { console.log('E') };
function logF() { console.log('F') };
function logG() { console.log('G') };
function logH() { console.log('H') };
function logI() { console.log('I') };
function logJ() { console.log('J') };

logA();
setTimeout(logG, 0);
Promise.resolve()
  .then(logC)
  .then(setTimeout(logH))
  .then(logD)
  .then(logE)
  .then(logF);
setTimeout(logI);
setTimeout(logJ);
logB();
function logA() { console.log('A') };
function logB() { console.log('B') };
function logC() { console.log('C') };
function logD() { console.log('D') };
function logE() { console.log('E') };
function logF() { console.log('F') };
function logG() { console.log('G') };
function logH() { console.log('H') };
function logI() { console.log('I') };
function logJ() { console.log('J') };

logA();
setTimeout(logG, 0);
Promise.resolve()
  .then(logC)
  .then(setTimeout(logH))
  .then(logD)
  .then(logE)
  .then(logF);
setTimeout(logI);
setTimeout(logJ);
logB();
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
process.nextTick(() => console.log('nextTick'));
console.log('current event loop');
setImmediate(() => console.log('I run immediately'))
process.nextTick(() => console.log('But I run before that'))
let count = 0
const cb = () => {
    console.log(`Processing nextTick cb ${++count}`)
    process.nextTick(cb)
}
setImmediate(() => console.log('setImmediate is called'))
setTimeout(() => console.log('setTimeout executed'), 100)
process.nextTick(cb)
console.log('Start')
let count = 0
const cb = () => {
    console.log(`Processing setImmediate cb ${++count}`)
    setImmediate(cb)
}
setImmediate(cb)
setTimeout(() => console.log('setTimeout executed'), 100)
console.log('Start')
console.log('Foo: Start', new Date().toLocaleTimeString());

setTimeout(() => {
  console.log(
    'Poo: To be called in 5 seconds ',
    new Date().toLocaleTimeString()
  );
}, 5000);

const waitlogForNseconds = seconds => {
  const startTime = new Date().getTime();
  const milliseconds = 1000;
  const endTime = startTime + seconds * milliseconds;
  let currTime = new Date().getTime();
  while (endTime > currTime) {
    currTime = new Date().getTime();
  }
  console.log(
    `Goo: To be called after ${seconds} End `,
    new Date().toLocaleTimeString()
  );
};

waitlogForNseconds(10);

console.log('Bar: ', new Date().toLocaleTimeString());
console.log('Foo: Start', new Date().toLocaleTimeString());

setTimeout(() => {
  console.log(
    'Poo: To be called in 5 seconds ',
    new Date().toLocaleTimeString()
  );
}, 5000);

const waitlogForNseconds = seconds => {
  const startTime = new Date().getTime();
  const milliseconds = 1000;
  const endTime = startTime + seconds * milliseconds;
  let currTime = new Date().getTime();
  while (endTime > currTime) {
    currTime = new Date().getTime();
  }
  console.log(
    `Goo: To be called after ${seconds} End `,
    new Date().toLocaleTimeString()
  );
};

waitlogForNseconds(10);

console.log('Bar: ', new Date().toLocaleTimeString());
const assert = require('assert');

const configs = {
  YEARLY_INTEREST_RATE: 4.0
};

const getSavingsAmount = amount => {
  return amount + amount * (configs.YEARLY_INTEREST_RATE / 100);
};

assert(getSavingsAmount(100) === 104);

configs.YEARLY_INTEREST_RATE = 3.0;

assert(getSavingsAmount(100) === 104);
const assert = require('assert');

const getSavingsAmount = (amount, interestRate) => {
  return amount + amount * (interestRate / 100);
};

assert(getSavingsAmount(100, 3) === 103);
assert(getSavingsAmount(100, 2) === 102);
assert(getSavingsAmount(100, 4) === 104); 
const foo = {
  'ONE':1,
  'TWO':2
};

const mapMultiplier = (params, multiplier) => {
  params.ONE = params.ONE * multiplier
  params.TWO = params.TWO * multiplier
  return params;
};

console.log(mapMultiplier(foo, 2));
console.log(mapMultiplier(foo, 3));
console.log(mapMultiplier(foo, 4));

// Value of foo { 'ONE': 1, 'TWO': 2 }
console.log('foo: ', foo);
const foo = {
  ONE: 1,
  TWO: 2
};
const mapMultiplier = (params, multiplier) => {
  // Only shallow clone works, deep clone is expensive and need other mechanisms
  const paramsCopy = { ...params }; // Object.freeze(params); //  Object.assign({}, params)
  paramsCopy.ONE = paramsCopy.ONE * multiplier;
  paramsCopy.TWO = paramsCopy.TWO * multiplier;
  return paramsCopy;
};
console.log(mapMultiplier(foo, 2));
console.log(mapMultiplier(foo, 3));
console.log(mapMultiplier(foo, 4));

// Value of foo { 'ONE': 1, 'TWO': 2 }
console.log('foo: ', foo);
/******** Array  ********/

// Instead of simple assigment
const a = Object.freeze([4, 5, 6]);
const b = [...[4, 5, 6]];

// Instead of: a.push(7, 8, 9);
const b = a.concat(7, 8, 9);
const c = [...a, 3]

// Instead of: a.pop();
const c = a.slice(0, -1);

// Instead of: a.unshift(1, 2, 3);
const d = [1, 2, 3].concat(a);

// Instead of: a.shift();
const e = a.slice(1);

/******** Maps ********/
const map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three']
]);

// Instead of: map.set(4, 'four');
const map2 = new Map([...map, [4, 'four']]);

// Instead of: map.delete(1);
const map3 = new Map([...map].filter(([key]) => key !== 1));

// Instead of: map.clear();
const map4 = new Map();

/******** Sets ********/

const set = new Set(['A', 'B', 'C']);

// Instead of: set.add('D');
const set2 = new Set([...set, 'D']);

// Instead of: set.delete('B');
const set3 = new Set([...set].filter(key => key !== 'B'));

// Instead of: set.clear();
const set4 = new Set();


/******** Array  ********/

// Instead of simple assigment
const a = Object.freeze([4, 5, 6]);
const b = [...[4, 5, 6]];

// Instead of: a.push(7, 8, 9);
const b = a.concat(7, 8, 9);
const c = [...a, 3]

// Instead of: a.pop();
const c = a.slice(0, -1);

// Instead of: a.unshift(1, 2, 3);
const d = [1, 2, 3].concat(a);

// Instead of: a.shift();
const e = a.slice(1);

/******** Maps ********/
const map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three']
]);

// Instead of: map.set(4, 'four');
const map2 = new Map([...map, [4, 'four']]);

// Instead of: map.delete(1);
const map3 = new Map([...map].filter(([key]) => key !== 1));

// Instead of: map.clear();
const map4 = new Map();

/******** Sets ********/

const set = new Set(['A', 'B', 'C']);

// Instead of: set.add('D');
const set2 = new Set([...set, 'D']);

// Instead of: set.delete('B');
const set3 = new Set([...set].filter(key => key !== 'B'));

// Instead of: set.clear();
const set4 = new Set();


/******** Array  ********/

// Instead of simple assigment
const a = Object.freeze([4, 5, 6]);
const b = [...[4, 5, 6]];

// Instead of: a.push(7, 8, 9);
const b = a.concat(7, 8, 9);
const c = [...a, 3]

// Instead of: a.pop();
const c = a.slice(0, -1);

// Instead of: a.unshift(1, 2, 3);
const d = [1, 2, 3].concat(a);

// Instead of: a.shift();
const e = a.slice(1);

/******** Maps ********/
const map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three']
]);

// Instead of: map.set(4, 'four');
const map2 = new Map([...map, [4, 'four']]);

// Instead of: map.delete(1);
const map3 = new Map([...map].filter(([key]) => key !== 1));

// Instead of: map.clear();
const map4 = new Map();

/******** Sets ********/

const set = new Set(['A', 'B', 'C']);

// Instead of: set.add('D');
const set2 = new Set([...set, 'D']);

// Instead of: set.delete('B');
const set3 = new Set([...set].filter(key => key !== 'B'));

// Instead of: set.clear();
const set4 = new Set();


const withLog = (fn) => {  
  return (...args) => {  
	console.log(`calling ${fn.name}`);  
	return fn(...args);  
  };  
};
const withLog = (fn) => {  
  return (...args) => {  
	console.log(`calling ${fn.name}`);  
	return fn(...args);  
  };  
};
const withLog = (fn) => {  
  return (...args) => {  
	console.log(`calling ${fn.name}`);  
	return fn(...args);  
  };  
};
const withLog = (fn) => {  
  return (...args) => {  
	console.log(`calling ${fn.name}`);  
	return fn(...args);  
  };  
};
const withLog = (fn) => {  
  return (...args) => {  
	console.log(`calling ${fn.name}`);  
	return fn(...args);  
  };  
};
const assert = require('assert');

const add = (a, b) => a + b;

assert(add(2, 3) === 5);
assert(add(2, 3) <= 6);
assert(add(2, 3) != 10);
const getSimpleText = text => {
  return text.toString().toLowerCase();
};

const getCurrentDateTime = () => new Date().toISOString();

const loggerWithTimeStamp = text => getCurrentDateTime() + ':  ' + getSimpleText(text);

const loggerWithTimeStampAndLevel = (text, level) => ` [ ${level.toUpperCase()} ] ${loggerWithTimeStamp(text)}`;

const loggerWithTimeStampAndLevelAndCallee = (text, level, callee) => {
  return 'Task: ' + callee + loggerWithTimeStampAndLevel(text, level);
};

const log = function(text, level) {
  if (level) {
    console[level](
      loggerWithTimeStampAndLevelAndCallee(text, level, log.caller.name)
    );
  } else {
    console.info(
      loggerWithTimeStampAndLevelAndCallee(text, 'info', log.caller.name)
    );
  }
};

(function run() {
  log('This is logger statement');
  log(Buffer.from('Something to log'), 'warn');
  log('This is logger statement', 'error');
  log('This is logger statement', 'error');
  log('This is logger statement', 'error');
})();
const assert = require('assert');

const getSavingsAmount = (amount, interestRate) => {
  return amount + amount * (interestRate / 100);
};

assert(getSavingsAmount(100, 3) === 103);
assert(getSavingsAmount(100, 2) === 102);
assert(getSavingsAmount(100, 4) === 104); 
const assert = require('assert');

const configs = {
  YEARLY_INTEREST_RATE: 4.0
};

const getSavingsAmount = amount => {
  return amount + amount * (configs.YEARLY_INTEREST_RATE / 100);
};

assert(getSavingsAmount(100) === 104);

configs.YEARLY_INTEREST_RATE = 3.0;

assert(getSavingsAmount(100) === 104);
const getSimpleText = text => {
  return text.toString().toLowerCase();
};

const getCurrentDateTime = () => new Date().toISOString();

const loggerWithTimeStamp = text => getCurrentDateTime() + ':  ' + getSimpleText(text);

const loggerWithTimeStampAndLevel = (text, level) => ` [ ${level.toUpperCase()} ] ${loggerWithTimeStamp(text)}`;

const loggerWithTimeStampAndLevelAndCallee = (text, level, callee) => {
  return 'Task: ' + callee + loggerWithTimeStampAndLevel(text, level);
};

const log = function(text, level) {
  if (level) {
    console[level](
      loggerWithTimeStampAndLevelAndCallee(text, level, log.caller.name)
    );
  } else {
    console.info(
      loggerWithTimeStampAndLevelAndCallee(text, 'info', log.caller.name)
    );
  }
};

(function run() {
  log('This is logger statement');
  log(Buffer.from('Something to log'), 'warn');
  log('This is logger statement', 'error');
  log('This is logger statement', 'error');
  log('This is logger statement', 'error');
})();
while (true) {
  const task = tasks().remove();
  execute(task);
}

Similiar Collections