add Ox.sub()

This commit is contained in:
rolux 2011-08-01 12:01:38 +02:00
parent e403b13cd1
commit 2f88a62ee4

View file

@ -365,10 +365,10 @@ Ox.every <f> Tests if every element of a collection satisfies a given condition
> Ox.every([true, true, true]) > Ox.every([true, true, true])
true true
@*/ @*/
Ox.every = function(obj, fn) { Ox.every = function(col, fn) {
return Ox.filter(Ox.values(obj), fn || function(v) { return Ox.filter(Ox.values(col), fn || function(v) {
return v; return v;
}).length == Ox.len(obj); }).length == Ox.len(col);
}; };
/*@ /*@
@ -383,10 +383,10 @@ Ox.filter <f> Filters a collection by a given condition
'foobar' 'foobar'
@*/ @*/
Ox.filter = function(obj, fn) { Ox.filter = function(col, fn) {
var type = Ox.typeOf(obj), var type = Ox.typeOf(col),
ret = type == 'array' ? [] : type == 'object' ? {} : ''; ret = type == 'array' ? [] : type == 'object' ? {} : '';
Ox.forEach(obj, function(v, k) { Ox.forEach(col, function(v, k) {
if (fn(v, k)) { if (fn(v, k)) {
if (type == 'array') { if (type == 'array') {
ret.push(v); ret.push(v);
@ -886,6 +886,34 @@ Ox.some = function(obj, fn) {
return Ox.filter(Ox.values(obj), fn).length > 0; return Ox.filter(Ox.values(obj), fn).length > 0;
}; };
/*@
Ox.substr <f> 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 <f> Returns the sum of the values of a collection Ox.sum <f> Returns the sum of the values of a collection
> Ox.sum(1, 2, 3) > Ox.sum(1, 2, 3)
@ -4255,13 +4283,11 @@ Ox.substr <f> A better <code>substr</code>
> Ox.substr('foobar', -5, -1) > Ox.substr('foobar', -5, -1)
"ooba" "ooba"
@*/ @*/
// fixme: this would be nice to have for arrays, too // deprecated, use Ox.sub()
Ox.substr = function(str, start, stop) { Ox.substr = function(str, start, stop) {
// fixme: needed? // fixme: needed?
stop = Ox.isUndefined(stop) ? str.length : stop; stop = Ox.isUndefined(stop) ? str.length : stop;
return str.substring( return str.substring(
start < 0 ? str.length + start : start,
stop < 0 ? str.length + stop : stop
); );
}; };