locked
RangedList - to display only the top 10 items of any Binding.List (Projection)

    General discussion

  • I came up with this today when I needed to display only 10 (out of many) items on a HubSection in my app.

    var createRangedList;
    createRangedList = function(base, from, to) {
      return base.createFiltered(function(item) {
        var index;
        index = base.indexOf(item);
        return index >= from && index < to;
      });
    };
    
    // Specs to check if its working
    return it("has 2 items out of 5", function() {
      var all, limited, limitedSorted, sorted;
      all = new WinJS.Binding.List([1, 2, 3, 4, 5]);
      limited = createRangedList(all, 0, 2);
      expect(limited).to.have.length(2);
      expect(limited.getAt(0)).to.equal(1);
      expect(limited.getAt(1)).to.equal(2);
      
      sorted = all.createSorted(function(a, b) {
        return b - a;
      });
      limitedSorted = createRangedList(sorted, 0, 2);
      
      // The items in the list should be in descending order
      expect(limitedSorted).to.have.length(2);
      expect(limitedSorted.getAt(0)).to.equal(5);
      expect(limitedSorted.getAt(1)).to.equal(4);
      
      // A push should only change the limitedSorted filtered list, because 666 would not be on top of it
      all.push(666);
    
      expect(limited.getAt(0)).to.equal(1);
      expect(limited.getAt(1)).to.equal(2);
      expect(limitedSorted.getAt(0)).to.equal(666);
      expect(limitedSorted.getAt(1)).to.equal(5);
    });

    I know the indexOf call on the base list is not the most efficient, but as a first try of a truly "live" top-list of any base list it works pretty well.

    Of course it also allows you to display the 10th-20th items, which makes it a good fit for (poor mans) paging :)

    Friday, June 13, 2014 9:51 PM