Skip to main content

Posts

featured

google-analytics | webdevhub

google-analytics | webdevhub
Recent posts

sorting-strings-with-accented-characters

Javascript has a native method  sort  that allows sorting arrays. Doing a simple  array.sort()  will treat each array entry as a string and sort it alphabetically. Also you can provide your  own custom sorting  function. [ 'Shanghai' , 'New York' , 'Mumbai' , 'Buenos Aires' ] . sort () ; // ["Buenos Aires", "Mumbai", "New York", "Shanghai"] But when you try order an array of non ASCII characters like this  ['é', 'a', 'ú', 'c'] , you will obtain a strange result  ['c', 'e', 'á', 'ú'] . That happens because sort works only with the English language. See the next example: // Spanish [ 'único' , 'árbol' , 'cosas' , 'fútbol' ] . sort () ; // ["cosas", "fútbol", "árbol", "único"] // bad order // German [ 'Woche' , 'wöchentlich' , 'wäre' , 'Wann...

improve-nested-conditionals

How can we improve and make a more efficient nested  if  statement in javascript? if (color) { if (color === 'black' ) { printBlackBackground () ; } else if (color === 'red' ) { printRedBackground () ; } else if (color === 'blue' ) { printBlueBackground () ; } else if (color === 'green' ) { printGreenBackground () ; } else { printYellowBackground () ; } } One way to improve the nested  if  statement would be using the  switch  statement. Although it is less verbose and is more ordered, it’s not recommended to use it because it’s so difficult to debug errors. Here’s  why . switch (color) { case 'black' : printBlackBackground () ; break ; case 'red' : printRedBackground () ; break ; case 'blue' : printBlueBackground () ; break ; case 'green' : printGr...

Inserting an item into an existing array

Inserting an item into an existing array Inserting an item into an existing array is a daily common task. You can add elements to the end of an array using push, to the beginning using unshift, or to the middle using splice. Those are known methods, but it doesn’t mean there isn’t a more performant way. Here we go: Adding an element at the end Adding an element at the end of the array is easy with push(), but it can be done in different ways. var arr = [ 1 , 2 , 3 , 4 , 5 ] ; var arr2 = [] ; arr . push ( 6 ) ; arr[arr . length ] = 6 ; arr2 = arr . concat ([ 6 ]) ; Both first methods modify the original array. Don’t believe me? Check the  jsperf Performance on mobile : Android (v4.2.2) arr.push(6);  and  arr[arr.length] = 6;  have the same performance // 3 319 694 ops/sec arr2 = arr.concat([6]);  50.61 % slower than the other two methods Chrome Mobile (v33.0.0) arr[arr.length] = 6;  // 6 125 975 ops/sec arr.push(6);  66.74 % slower arr2 =...