Skip to content

Instantly share code, notes, and snippets.

@mavame
Created September 12, 2017 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mavame/a839c2652a1282f0c45b55be78e378d9 to your computer and use it in GitHub Desktop.
Save mavame/a839c2652a1282f0c45b55be78e378d9 to your computer and use it in GitHub Desktop.
/**
* 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
Copy link
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