提交 d49cb345 编写于 作者: M Matt Zabriskie

Updating forEach to handle non iterable values

上级 0c7236b2
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
'use strict';
function isArrayLike(obj) {
return obj.constructor === Array || typeof obj.callee === 'function';
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
......@@ -13,12 +18,20 @@
* @param {Function} fn The callback to invoke for each item
*/
module.exports = function forEach(obj, fn) {
if (typeof obj !== 'object') {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
var isArray = isArrayLike(obj);
// Force an array if not already something iterable
if (typeof obj !== 'object' && !isArray) {
obj = [obj];
}
// Iterate over array values
if (obj.constructor === Array || typeof obj.callee === 'function') {
if (isArray) {
for (var i=0, l=obj.length; i<l; i++) {
fn.call(null, obj[i], i, obj);
}
......
......@@ -11,10 +11,6 @@ var forEach = require('./forEach');
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
if (typeof fns === 'function') {
return fns(data, headers);
}
forEach(fns, function (fn) {
data = fn(data, headers);
});
......
......@@ -29,5 +29,27 @@ module.exports = {
test.equal(keys, 'bar');
test.equal(vals, 6);
test.done();
},
testUndefined: function (test) {
var count = 0;
forEach(undefined, function () {
count++;
});
test.equals(count, 0);
test.done();
},
testFunction: function (test) {
var count = 0;
forEach(function () {}, function () {
count++;
})
test.equals(count, 1);
test.done();
}
};
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册