Posts

Showing posts from September, 2024

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...