Skip to content

Instantly share code, notes, and snippets.

@loginx
Created February 3, 2011 22:04

Revisions

  1. loginx revised this gist Feb 17, 2011. 1 changed file with 16 additions and 1 deletion.
    17 changes: 16 additions & 1 deletion gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,9 @@
    /**
    * Underscore.js mixin to emulate Ruby's Enumerable#each_slice method.
    * http://www.ruby-doc.org/core/classes/Enumerable.html#M001514
    *
    */

    _.mixin({
    each_slice: function(obj, slice_size, iterator, context) {
    var collection = obj.map(function(item) { return item; });
    @@ -9,4 +15,13 @@ _.mixin({
    }
    return;
    }
    });
    });

    /* Example:
    >>> _([1,2,3,4,5,6,7,8,9,10]).each_slice(4, function(slice) { console.log(slice); })
    [1, 2, 3, 4]
    [5, 6, 7, 8]
    [9, 10]
    */
  2. loginx revised this gist Feb 9, 2011. 1 changed file with 6 additions and 9 deletions.
    15 changes: 6 additions & 9 deletions gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -1,15 +1,12 @@
    _.mixin({
    each_slice: function(obj, slice_size, iterator, context) {
    console.log(obj);
    if (!_.isArray(obj)) {
    return;
    }
    var collection = obj.map(function(item) { return item; });

    for (var i = 0, s = Math.ceil(obj.length/slice_size); i < s; i++) {
    iterator.call(context, obj.slice(i*slice_size, (i*slice_size)+slice_size), obj);
    if (typeof collection.slice !== 'undefined') {
    for (var i = 0, s = Math.ceil(collection.length/slice_size); i < s; i++) {
    iterator.call(context, _(collection).slice(i*slice_size, (i*slice_size)+slice_size), obj);
    }
    }

    return;

    return;
    }
    });
  3. loginx renamed this gist Feb 3, 2011. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  4. loginx created this gist Feb 3, 2011.
    15 changes: 15 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    _.mixin({
    each_slice: function(obj, slice_size, iterator, context) {
    console.log(obj);
    if (!_.isArray(obj)) {
    return;
    }

    for (var i = 0, s = Math.ceil(obj.length/slice_size); i < s; i++) {
    iterator.call(context, obj.slice(i*slice_size, (i*slice_size)+slice_size), obj);
    }

    return;

    }
    });