forked from 0x2620/oxjs
less obscure Ox.map
This commit is contained in:
parent
33390069b9
commit
12cf77cef5
21 changed files with 125 additions and 101 deletions
|
|
@ -111,6 +111,7 @@ Ox.filter <f> Filters a collection by a given condition
|
|||
@*/
|
||||
Ox.filter = function(col, fn, that) {
|
||||
var ret, type = Ox.typeOf(col);
|
||||
fn = fn || Ox.identity;
|
||||
if (type == 'object') {
|
||||
ret = {};
|
||||
Ox.forEach(col, function(val, key) {
|
||||
|
|
@ -303,6 +304,16 @@ Ox.indexOf = function(col, fn) {
|
|||
return index == col.length ? -1 : index;
|
||||
};
|
||||
|
||||
// FIXME: use this instead of `Ox.filter(Ox.map())` when it's just about getting
|
||||
// the original indices
|
||||
Ox.indicesOf = function(col, fn) {
|
||||
return Ox.map(col, function(val, i) {
|
||||
return fn(val) ? i : null;
|
||||
}).filter(function(index) {
|
||||
return index !== null;
|
||||
});
|
||||
};
|
||||
|
||||
/*@
|
||||
Ox.isEmpty <f> Tests if a value is an empty array, object or string
|
||||
(value) -> <b> True if the value is an empty array, object or string
|
||||
|
|
@ -460,8 +471,7 @@ Ox.makeObject = function(arr) {
|
|||
/*@
|
||||
Ox.map <f> Transforms the values of an array, object or string
|
||||
Unlike <code>[].map()</code>, <code>Ox.map()</code> works for arrays,
|
||||
objects and strings. Returning <code>null</code> from the iterator
|
||||
function will remove the element from the collection.
|
||||
objects and strings.
|
||||
> Ox.map([0, 0, 0], function(v, i) { return v == i; })
|
||||
[true, false, false]
|
||||
> Ox.map({a: 'a', b: 'a', c: 'a'}, function(v, k) { return v == k; })
|
||||
|
|
@ -474,21 +484,19 @@ Ox.map <f> Transforms the values of an array, object or string
|
|||
# > Ox.map([,], function(v, i) { return i; })
|
||||
# [0]
|
||||
@*/
|
||||
|
||||
// FIXME: it would sometimes be nice to have Ox.map(3, function(i) {...})
|
||||
// instead of Ox.range(3).map(function(i) {...})
|
||||
|
||||
Ox.map = function(obj, fn) {
|
||||
// fixme: return null to filter out may be a bit esoteric
|
||||
var isObject = Ox.isObject(obj),
|
||||
ret = isObject ? {} : [];
|
||||
Ox.forEach(obj, function(val, key) {
|
||||
// FIXME: is there any reason for this strange assignment?
|
||||
var map;
|
||||
if ((map = fn(val, key)) !== null) {
|
||||
ret[isObject ? key : ret.length] = map;
|
||||
Ox.map = function(col, fn, that) {
|
||||
var type = Ox.typeOf(col), ret;
|
||||
if (type == 'object') {
|
||||
ret = {};
|
||||
Ox.forEach(col, function(val, key) {
|
||||
ret[key] = fn.call(that, val, key, col);
|
||||
});
|
||||
} else {
|
||||
ret = Ox.toArray(col).map(fn);
|
||||
if (type == 'string') {
|
||||
ret = ret.join('');
|
||||
}
|
||||
});
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue