show hide blocks using promises

Animation to show and hide a list of blocks.

by Richard Hunter

HTML

<button data-show>show</button>
<button data-hide>hide</button>
<ul data-container>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

SCSS

ul {
    width : 200px;
    margin : 100px auto;
    background : lightblue;
    list-style : none;
    padding : 0;
    overflow : hidden;
}
li {
    width : 50%;
    height : 100px;
    float : left;
    visibility : hidden;
    background : red;
}

JavaScript

var listItems = $('[data-container] li');

 $('[data-show]').click(function () {
     
     var list = new Iterator(listItems, true);

     function showListItem(li) {
         
         $(li).css({
             visibility: "visible"
         });
     }

     processList(list, showListItem).then(function() {
     
         console.log("job done");
     });

 });

 $('[data-hide]').click(function () {
     
     var list = new Iterator(listItems, false);
     
     function hideListItem(li) {
         $(li).css({
             visibility: "hidden"
         });
     }

     processList(list, hideListItem);
 });


 function Iterator(list, direction) {

     this.list = list;
     this.index = 0;
     this.length = list.length;
     //  boolean: if false we iterate in reverse direction
     this.direction = direction;
 }
 Iterator.prototype = {

     hasNext: function () {
         return this.index < this.length;
     },
     next: function () {

         if (this.direction) {
             return this.list.get(this.index++);    
         } else {        
             return this.list.get(this.length - (++this.index));
         }
     }
 }


 function foo(link, callback) {
 
     return new Promise(function(resolve, reject){
     
         setTimeout(function() {
            
             callback(link);
             resolve();
         
         }, 500)    
     });
 }
 
 
 function processList(list, strategy) {
     
     var sequence = Promise.resolve();
     
     while(list.hasNext()) {
         
         var link = list.next();
         
         (function(link) {
                  
             sequence = sequence.then(function() { 
                 
                 return  foo(link, strategy);
        
             });
             
         })(link);
         
     }
     
     return sequence;

}