Posts

Async logger service using javascript

 class LoggerService {   packSizeLimit = 3   isServerReady = true   queue = []      getIsServerReady() {     return this.isServerReady;   }   sendEventsToQueue(data) {     this.queue.push(data);     this.sendEvents();   }   sendEvents() {     if(this.getIsServerReady()) {       const pack = this.queue.splice(0, this.packSizeLimit);       this.sendEventsToServer(pack);     }   }   // max 3 (packSizeLimit) events at a time   // and only after the promise returns success response   sendEventsToServer(list) {     this.isServerReady = false;     const promise = new Promise((res, rej) => {       setTimeout(() => {         res()       }, 2000)     });     promise.then(res => {       this.isServerReady = true;      ...

NextIva Round 1 for Lead React Developer position

const p1 = Promise . resolve ( 1 ); const p2 = Promise . reject ( 'Error!' ); const p3 = Promise . resolve ( 3 ); // Promise.all([p1, p2, p3]) // .then((result) =>console.log('All:', result)) // .catch((error) =>console.log('Caught:', error)); // Promise.allSettled([p1, p2, p3]) // .then((result) =>console.log('All Settled:', result)); // all - Caught: Error! // allSettled - 'All Settled: [1, 'Error!', 3]' // console.log('Start'); // setTimeout(() => console.log('Timeout 1'), 0); // Promise.resolve().then(() => console.log('Promise 1')); // Promise.resolve().then(() => { // console.log('Promise 2'); // setTimeout(() => console.log('Timeout 2'), 0) // }); // console.log('End'); // () => console.log('Timeout 1') // console.log('Promise 1') //co...

Examples of function currying using javascript

 Examples of function currying using javascript export function transform ( str ) { // // Input: a3b3c6d5 // Output: aaaaabbbccccccddddd const strArray = str . split ( '' ); const map = {}; let lastChar = strArray [ 0 ]; let tmp = '' strArray . forEach ( char => { if ( isNaN ( char )) { map [ char ] = 0 ; if ( lastChar ) { map [ lastChar ] = Number ( tmp ); lastChar = char ; tmp = '' ; } } else { tmp += char ; } }) // map last characters repition here if ( tmp ) { map [ lastChar ] = Number ( tmp ); tmp = '' ; } let output = '' ; Object . keys ( map ). map ( key => { let charRepeatation = map [ key ]; for ( let i = 0 ; i < charRepeatation ; i ++) { output += key ; } }) return output ; } export function transformWithTimer ( input ) { var promise = new Promise ( res => { setTimeout (() =...

Flatten a nested object using javascript

Question Flatten the given nested object. The nesting can be upto n levels. For the below input const input = {   a: 10 ,   b: 'foo' ,   c: {     d: 'bar' ,     e: false ,     f: {       g: 'random' ,     },   },   d: 'test' , }; the output should look like this: // Output = {a: 10, b: 'foo', c.d: 'bar', c.e: false, c.f.g: 'random', d: test} Solution Lets write a function to flatten the above object. // Lets take a temporary object to save the flatten values let output = {}; function formatObject ( object , prefix ) {     // iterate over the attributes of the current object   Object . keys ( object ). forEach (( key ) => {     let value = object [ key ];     if ( typeof value !== 'object' ) {       console . log ( 'if 1: ' , value , prefix );       if ( prefix ) {         // ex: c.f.g: 'random'   ...

Write a polyfill for Array.map in javascript

What is Aray.map? Array.map accepts a callback function, executes the same over the original array and returns a new array.   //Example: const arr = ar1.map(x => x*2) What do we need a polyfill? We need polyfills to support the  old browsers  for the new methods like Array.map etc. introduced in the latest ecmascript. Polyfill for Array.map Lets write a polyfill named myMap. Note: " this " will contain the original array passed through the polyfill function. function myMap ( fun ) {   if ( this === null || this === undefined ) {     console . log ( 'myMap is iterating over an empty list.' );   }   // validating function   if ( typeof fun !== 'function' ) {     console . log ( 'myMap is missing the callback function as a parameter.' );   }   // get the original array   var oArray = this ;   let output = [];   console . log ( 'original array: ' , this , arguments );   oArray . forEach...

Write javascript polyfill for array.reduce

  // Example: Predefined Array.reduce // let arr = [1,2]  // arr.reduce((total, current) => total, initialvalue) // let newArr = arr.reduce((total, current) => total + current,  0) // console.log('hello new: ', newArr) /* Polyfill for reduce */ function myreduce(cb, init) { let copyArr = this;     let arrLen = copyArr.length;      // output   let acc = init;      // traverse right to left   while(arrLen) {   let currItem = copyArr[arrLen - 1];   acc = cb(acc, currItem);     arrLen--;   }   return acc; } Array.prototype.myreduce = myreduce; console.log('Polyfill: ', [1, 2].myreduce((total, current) => total + current,  0)); // Output: 3

Find the longest substring in a given string.

  Find the longest substring in a given string. Agoda round 1 on 31/05/2023 by Peter and Kuma Example #1: input: 'abcabc' output: 3 Example #2: input: 'bbbb' output: 1 Example #3: input: 'abb' output: 2 function solution ( s ) { const strLen = s . length ; let max = 0 ; let long = []; // b for ( let j = 0 ; j < strLen ; j ++) { // j = 1, b if ( long . indexOf ( s [ j ]) > - 1 ) { long = []; // push the curr char to the long list long . push ( s [ j ]); } else { // push the curr distinct char to the long list long . push ( s [ j ]); const longLen = long . length ; if ( longLen > max ) { max = longLen ; } } } return max ; } // Time complexity can be improved to O(n) by putting characters of the longest substring ('long' in the above code) in a map instead of list. /*{ ...