Sunday, July 12, 2015

Calling JavaScript inner array methods

JavaScript array methods may be placed inside an outer array method. When the outer method is run, the inner method is run against the current array element. In this post, the array that will be used is still the objects containing computer units issued to persons. The objective is to determine the percentage of an individual free HD space against the total HD free space:


The standard approach using a for() loops would be as follows:

<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 
 var totalFree = 0;
 
 for(var i =0; i < units.length; i++){
  totalFree += units[i].GBHDFree;
 }
 
 var freePercent = [];
 
 for(var i =0; i < units.length; i++){
  freePercent.push((units[i].GBHDFree/totalFree) * 100);
 }
 
 console.log(freePercent);
 </script>

An alternative approach is to use the array map() method to create a parallel array to the units array. The map() method calls a function that goes through each object element and determines the elements free HD space.


The function then calls a combine units array map() and reduce() methods. The map() creates a parallel array of free HD space for each units object element. The reduce() computes the total of each element (Free HD space) in the parallel array.


The combine map() and reduce() are the inner methods called by the function in the outer map() method. The code snipper is listed below:
<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 var getPercentageFree = function(unit){
  var free = unit.GBHDFree;
  var totalFree = units.map(function(unit){return unit.GBHDFree}).reduce(function(start, current){
   return start + current;
  }, 0);
  return (free / totalFree) * 100;
 }
 
 console.log(units.map(getPercentageFree));
 
 </script>

The full code is available at:
https://github.com/jundolor/JavaScript/blob/master/callinginnerarraymethods.html

Monday, July 6, 2015

Combining JavaScript Array Methods filter() and reduce()

JavaScript array methods may be combined to generate a result. The code study in this post will filter selected array elements and summarize the data. The JavaScript array methods that will be combined are filter() and reduce().

The array which will be the subject of the code study is shown below:


Each element of the array is an object with key-value pairs. The idea of the array is to provide information on computers that have been issued to various persons., The name key identifies the person, GBHD stands for Giga Byte HD- the total capacity of the HD, GBHDFree stands for Guga Byte HD Free-meaning the free space on the HD, and OS-the operating system of the computer

Using method filter(), as shown in the code snippet below, the array is narrowed down to computer units with MacOS as the operating system:
      
<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 
 var filterOS = function(u){
  return u.OS == "MacOS"
 }
 
 console.log("MacOS Units:" ,units.filter(filterOS));
 //MacOS Units: {name: Bert...}, {name: Grover...}, {name: Count...}
 
</script>

The method filter() calls the function filterOS(). Each array element, an object is passed to the parameter. The function returns back the object has "MacOS" as the value to the OS key. All other objects are filtered out. An array of objects with key-value pair of OS: "MacOS" is returned. Note that the original array is retained.

The method reduce(), as shown in the code snippet below calls the function mostHDFree(). The function, in turn, goes thru each array element, an object, to see which has the biggest GBHDFree value.

<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 
 
 var mostHDFree = function(start, current){
  if(start.GBHDFree > current.GBHDFree) return start;
  else return current;
 }
 
 console.log("Unit with most HD free space",units.reduce(mostHDFree));
 //Unit with most HD free space {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"}
</script>

The methods filter() and reduce() may be combined to determine what objects with key-value pair of OS: "MacOS" has the most GBHDFree value.

JavaScript starts with the leftmost method and soon as a result is generated, calls the next method to the right, passing the generated result. The cycle will continue for additional methods to the right.

In the case of the filter() and reduce method() combine, the filter() returns an array of objects with OS: "MacOS". The array is passed to the reduce() method which selects the object with the most GBHDFree value.

The code snippet is listed below:
<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 
 var filterOS = function(u){
  return u.OS == "MacOS"
 }
 
 var mostHDFree = function(start, current){
  if(start.GBHDFree > current.GBHDFree) return start;
  else return current;
 }
 
 console.log("MacOS with most HD space free",units.filter(filterOS).reduce(mostHDFree));
 //MacOS with most HD space free {name: "Bert"...}, 
</script>

The full code can be downloaded at:
https://github.com/jundolor/JavaScript-Combine-Array-Methods/blob/master/index.html

Monday, June 29, 2015

JavaScript Every vs. Some Array Methods

JavaScript arrays comes with methods that behave like the And && and Or || operators.

The every method takes a function with each array element as parameter. The function tests each array element, and if the test of all array elements evaluate to True, the method returns a true value. If at least one test evaluates to false, the method now returns a false value. The method behaves very much like expressions having And && operator, wherein the expression will only return true if the evaluated expression to the left and to the right evaluates to true.

The some method also takes a function with each array element as parameter. However, the function only needs to determine if at least one array element evaluates the test to be true. The method therefore behaves similar to expressions having the Or operator, wherein the either expression to the left of right needs to evaluate to true for the operator to return true.

In the sample the code snippet below, the inventory of PC issued to each employee logs how much RAM and HD memories are installed.

<script>
    var units =[{name: "Ernie", GBRAM: 1024, GBHD: 512000}, {name: "Bert", GBRAM: 2048, GBHD: 512000}, {name: "Kermit", GBRAM: 3072, GBHD: 512000}];
    var checkMem = function(u){
        return u.GBRAM > 1024;
    }
    console.log("Employees PC Units Inventory..");
    units.forEach(function(p){console.log(p.name)})
    console.log("All Units having more than 1 GB RAM",units.every(checkMem));
    console.log("Some Units having more than 1 GB RAM",units.some(checkMem));
</script>

An array units contains objects having name, GBRAM and GBHD as keys. The name key identifies the employee. The GBRAM  and GBHD records how much Giga Byte memory is installed in the RAM and HD.



The line unit.forEach() goes through each array element without having to use any of JavaScript loop control. The method takes a function as a parameter. The function then takes each unit array element and passed to its defined parameter p. Each array elemnt is an object with key value pairs.The function logs the value of the name key in the array element object.

The output is show below:

The function checkMem will accept an element object from the array unit. The test if the object GBRAM key is greater than 1024 is returned.

Array calls to every and some methods are made, wherein both method takes the function checkMem as the parameter. Both every() and some() methods will go thru each element object and pass it to checkMem.

The array elements to be passed to checkMem are shown below:
Checking each array element object, both every() and some() methods will evaluate the first element object (name: "Ernie") to be false, but will evaluate the rest to true.

Since every() method returns true only if all array elements evaluated in its function parameter is true, then the method will not return true. On the other hand, some() method only needs one array element to evaluate to true in the function test, it will return a true value. The complete console output is shown below:

The full code can be accessed on the link below:
https://github.com/jundolor/JavaScript-Every-vs-Some/blob/master/index.html

Monday, May 25, 2015

JavaScript Array Reduce Method

JavaScript loops such as for and while provides a way to do useful work on each array element, i.e code below:
<script>
	var numbers = [5, 2, 15, 7, 9, 3, 8, 25, 3, 10, 11];
	for(var i = 0; i < numbers.length; i++){
		console.log(numbers[i]);
	}
</script>

The for loop goes through each element in the array and logs the value to the browser console.

Another useful JavaScript feature to go through each array element is by using the method reduce built-in on arrays. The method passes through each array element to reduce the values to a single value. This can be used to accumulate the element values into a single value.

The code below takes an array of numbers and uses the reduce method to get the element with the highest value divisible by the first element value:

The array numbers holds integer values for each of its element. The JavaScript code is to take the first element and divide the remaining elements by the value. The code checks if the quotient is divisible (no remainder), and determines which divisible value is the highest.

The array numbers has 5 as the value of the first element. Scanning the remaining elements, we see that there are three element values divisible by 5: 15, 25 and 10.
The variable divisor takes the value of the first array element. This is the value which array elements starting from the second up to the last will be divided by. 
The reduce method of the array has a callback function as its parameter. Callback functions, in turn, can have four parameters: previous value, current value, index and the array calling the reduce method.
In the code provided, only two parameters will be used. The start will hold the previous value passed to the callback, while the current will hold the current element in the callback. 

On the first loop of the reduce method, start parameter is initialized to the first array element value, 5 while the current parameter takes the second array element value, 2:
The current value, 2 is divided by the divisor value, 5. Since divisor was declared outside the callback method, the method can "see" or access the divisor. Since the quotient will return a value, the condition check will return a True value. The True value is reversed, and the condition check is evaluated to false. the first loop of the reduce method will then return the start value of 5.

On the next loop, the reduce method will assign the next element value, 15 to the current parameter. The start parameter takes the returned value of the previous loop, 5. The quotient of the current value 15 over the divisor, 5 will yield a value of zero, corresponding to false, which is then reversed to true. 
The check of current value, 15 greater than start value, 5 will evaluate to true. The current value, 15 is then returned. On the next, loop, the start parameter will now take this value.

On the loop that follows, the reduce method will assign the value of the next array element, 7 to the current parameter. The start parameter takes the returned value from the previous loop, which is 15. The quotient of the current value, 7 over the divisor, 5 will yield a value, corresponding to true, which is reversed to false. The loop will return the start value, 15.
 

The start value of 15 is retained, until the reduce method assigns the current parameter to array value 25. The loop will then return the value 25.
The start value of 25 will be retained even until the reduce method loops through the last array element. When the reduce method reaches the array element value 10, the loop determines that 10 is divisible by 5. However, the check of current value 10 greater than start value will evaluate to false. The loop will still return the value 25.
The full code can be accessed on my GitHib account:

Resources on array reduce method may accessed on the links below:



Saturday, May 16, 2015

Bootstrap Cheat Code for WordPress Thumbnail Mobile Responsiveness

Using the_post_thumbnail() in a WordPress loop displays the post featured image as a thumbnail to the post article. The first parameter size lets setting or customizing the width and height dimensions for the thumbnail. However, I wanted a flexibility for my Bootstrap based WordPress theme wherein the post thumbnail will display in a smaller size in mobile. In short, I wanted a post thumbnail mobile responsiveness on its display. The WordPress loop uses a Media Object to display the title, time posted, excerpt and of course, the thumbnail. A sample loop is shown below:
The Media Object calls the_post_thumbnail() while passing the 'thumbnail' parameter. The 'thumbnail' size is set to 150x150:

When the theme is rendered, WordPress set the width and height attributes to 150. I could have used CSS3's media query, but was not sure is it could have overwritten the width and height attributes. I decided come up with my own cheat code to display the thumbnail in a different size on mobiles:
The cheat involves using two image links. The first image link passes 'thumbnail' as the size parameter. The classes "hidden-xs hidden-sm" makes sure that the image will not display on mobile sized devices. This makes sure that the image is displayed in traditional desktop or laptop computers. The second image link passes array(50,50) as the size parameter. The thumbnail is displayed in 50px width and height. The classes "hidden-md hidden-lg" makes sure that the image will not display on computers with medium or large screens, i.e. desktop or laptop computers. This makes sure that the image is displayed on mobile devices. The WordPress loop code with the Bootstrap cheat is listed below
<?php 
if(have_posts()): 
while (have_posts()): the_post(); 
?>
<div class="media">
 <a href="#" class="pull-left hidden-xs hidden-sm">
  <?php the_post_thumbnail('thumbnail', array( 'class' => 'media-object img-rounded' )); ?>
 </a>
 <a href="#" class="pull-left hidden-md hidden-lg">
  <?php the_post_thumbnail(array(50,50), array( 'class' => 'media-object img-rounded' )); ?>
 </a>
 <div class="media-body">
  <h4 class="media-heading"><?php the_title(); ?> <small>Posted on<?php the_time('F j, Y'); ?></small></h4>
  <p><small><?php echo(get_the_excerpt()); ?></small></p>
  <p><a href="<?php the_permalink(); ?>" class="btn btn-primary">Read More</a>
  </p>
 </div>
</div>
<?php endwhile; ?>
<?php else: ?>
<?php endif; ?>

Tuesday, March 3, 2015

Applying Bootstrap Styles to WordPress Feature Image

For WordPress themes that are based on Bootstrap framework, applying styles such as circled, rounded image or thumbnails provides one way to enhance featured image appearances.

In the screenshot below, a feature image is displayed together with a loop post:

I've used the function the_post_thumbnail() to display the feature image:








Bootstrap circled image style can be applied to the featured image by using the arguments parameter to pass the corresponding class style.


The function the_post_thumbnail() was modified to take 'thumbnail' as the first parameter to define the size and 'array(,,,' to define the attributes. Take note of the Bootstrap image circle style added to the class

The code for the post loop together with the Bootstrap style on the featured image is listed below:

<?php if(have_posts()): while (have_posts()): the_post(); ?>
  <div class="col-lg-6" style="margin-bottom:5px;">
    <div class="media">
      <a href="#" class="pull-left">
        <?php the_post_thumbnail('thumbnail', array( 'class' => 'media-object img-circle' )); ?>
      </a>
    <div class="media-body">
      <h3 class="media-heading"><?php the_title(); ?>. <small><?php echo(get_the_excerpt()); ?></small></h3>
    </div>
    </div>
  </div>
<?php endwhile; ?>