Wednesday, December 27, 2017

JavaScript ES6 filter(), take() and range() with iterator


FuncJS Github Repo: FuncJS

      //

      let filter = function * (items, predicate) {

          for(let item of items)
              if(predicate(item))
                  yield item;
      }

      let take = function * (items, number) {

          let count = 0;
          if(number < 1) return;
          for(let item of items) {

              yield item;
              count += 1;
              if(count == number) return;
          }
      }
      
      let range = function * (start, end) { 
        
        let current = start;
        while(current <= end) {

          let delta = yield current;
          current += delta || 1;
        }
      }

      let count   = 0;
      let found   = null;
      let names   = ["Joy","Sue","Bob","Tom", "Sophie"];

      for(let e of take( filter( names, e => e.startsWith("S")), 1 ) ) {

          count += 1;
          found = e;
      }
 
      
      let result    = [];
      let iterator  = range(1, 10);
      let next      = iterator.next();

      while(!next.done) {

        result.push(next.value);
        next = iterator.next(2);
      }

No comments:

Post a Comment