Skip to content

Instantly share code, notes, and snippets.

@mavame mavame/forEach.js
Created Sep 12, 2017

Embed
What would you like to do?
/**
* Maps a callback to an element in an array-like object
* Basically a copy of underscore's _.each
* source: http://underscorejs.org/docs/underscore.html#section-20
*/
export function forEach(obj, iteratee, context) {
let ctx = this;
const isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
const has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
const _keys = function(obj) {
if (!isObject(obj)) return [];
if (Object.keys) return Object.keys(obj);
var keys = [];
for (var key in obj) if (has(obj, key)) keys.push(key);
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// source: https://github.com/darsain/isarraylike/blob/master/index.js
const isArrayLike = function(value, complex) {
return value
&& typeof value === 'object'
&& typeof value.length === 'number'
&& value.length >= 0
&& value.length % 1 === 0
&& (!complex || typeof value.splice === 'function');
}
if (context !== void 0) {
ctx = context;
}
if (isArrayLike(obj)) {
for (let i = 0, length = obj.length; i < length; i++) {
iteratee.call(ctx, obj[i], i, obj);
}
} else {
const keys = _keys(obj);
for (let i = 0, length = keys.length; i < length; i++) {
iteratee.call(ctx, obj[keys[i]], keys[i], obj);
}
}
return obj;
}
@mavame

This comment has been minimized.

Copy link
Owner Author

mavame commented Sep 12, 2017

Makes iterating through things like a NodeList simple in browsers that don't support NodeList.prototype.forEach, so it's best to do:
forEach(document.querySelectorAll('.my-component'), (el, idx) => { .. });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.