Skip to main content

Posts

Showing posts from November, 2020

use Map instead of Array with sort

  const input = 'i wanter Cats and dogs.' const convert = ( input ) => { const arr = input . substring ( 0 , input . length - 1 ). split ( ' ' ) const result = new Map () arr . forEach ( item => { const key = item . length if ( result . has ( key )){ result . set ( item . length , result . get ( key ) + ' ' + item ) } else result . set ( item . length , item ) }) const sorted = new Map ([... result . entries ()]. sort ()) let sentense = '' const values = Array . from ( sorted . values ()) values . forEach (( value , i ) => { const word = value . toLowerCase () if ( i === 0 ) sentense = sentense . concat ( word . substring ( 0 , 1 ). toUpperCase ()). concat ( word . substring ( 1 )) else sentense = sentense . concat ( word ) if ( i === values . length - 1 ) ...

for loop in javascript - promise - .eslintrc for "for of"

the vast majority of cases  map ,  forEach ,  find  etc. can be used.  async function printFiles () { const files = await getFilePaths(); await Promise.all(files. map (async (file) => { const contents = await fs.readFile(file, 'utf8') console.log(contents) })); } const inventory = [ { name : 'apples' , quantity : 2 } , { name : 'bananas' , quantity : 0 } , { name : 'cherries' , quantity : 5 } ] ; const result = inventory . find ( ( { name } ) => name === 'cherries' ) ;   function getFirstMatching(array) { for (let item of array) { const result = heavyTransform(item); if (result) { return result; } } } Specifically this shuts down the whole no-restricted-syntax. If you want to cherry-pick, here is the current definition: 'no-restricted-syntax' : [ 'error' , { selector : 'ForInStatement' , message...

Closures in Javascript

function add ( num ) { var counter = 0 ; return function ( num ) { counter += num return counter } } const addValue1 = add (); console . log ( addValue1 ( 2 )) console . log ( addValue1 ( 4 )) console . log ( addValue1 ( 1 )) console . log ( addValue1 ( 9 )) console . log ( addValue1 ( 1 )) const addValue2 = add (); console . log ( addValue2 ( 10 )) console . log ( addValue2 ( 20 ))