diff --git a/source/Ox.js b/source/Ox.js index 9d000683..12102fb3 100644 --- a/source/Ox.js +++ b/source/Ox.js @@ -365,10 +365,10 @@ Ox.every Tests if every element of a collection satisfies a given condition > Ox.every([true, true, true]) true @*/ -Ox.every = function(obj, fn) { - return Ox.filter(Ox.values(obj), fn || function(v) { +Ox.every = function(col, fn) { + return Ox.filter(Ox.values(col), fn || function(v) { return v; - }).length == Ox.len(obj); + }).length == Ox.len(col); }; /*@ @@ -383,10 +383,10 @@ Ox.filter Filters a collection by a given condition 'foobar' @*/ -Ox.filter = function(obj, fn) { - var type = Ox.typeOf(obj), +Ox.filter = function(col, fn) { + var type = Ox.typeOf(col), ret = type == 'array' ? [] : type == 'object' ? {} : ''; - Ox.forEach(obj, function(v, k) { + Ox.forEach(col, function(v, k) { if (fn(v, k)) { if (type == 'array') { ret.push(v); @@ -886,6 +886,34 @@ Ox.some = function(obj, fn) { return Ox.filter(Ox.values(obj), fn).length > 0; }; +/*@ +Ox.substr Returns a substring or sub-array + Ox.sub behaves like collection[start:stop] in Python + (or, for strings, like str.substring() with negative values for stop) + > Ox.sub([1, 2, 3], 1, -1) + [2] + > Ox.sub('foobar', 1) + "oobar" + > Ox.sub('foobar', -1) + "r" + > Ox.sub('foobar', 1, 5) + "ooba" + > Ox.sub('foobar', 1, -1) + "ooba" + > Ox.sub('foobar', -5, 5) + "ooba" + > Ox.sub('foobar', -5, -1) + "ooba" +@*/ +Ox.sub = function(col, start, stop) { + stop = Ox.isUndefined(stop) ? col.length : stop; + start = start < 0 ? col.length + start : start; + stop = stop < 0 ? col.length + stop : stop; + return Ox.isArray(col) ? Ox.filter(col, function(val, key) { + return key >= start && key < stop; + }) : col.substring(start, stop); +} + /*@ Ox.sum Returns the sum of the values of a collection > Ox.sum(1, 2, 3) @@ -4255,13 +4283,11 @@ Ox.substr A better substr > Ox.substr('foobar', -5, -1) "ooba" @*/ -// fixme: this would be nice to have for arrays, too +// deprecated, use Ox.sub() Ox.substr = function(str, start, stop) { // fixme: needed? stop = Ox.isUndefined(stop) ? str.length : stop; return str.substring( - start < 0 ? str.length + start : start, - stop < 0 ? str.length + stop : stop ); };