Created
September 12, 2017 00:23
-
-
Save mavame/a839c2652a1282f0c45b55be78e378d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Makes iterating through things like a
NodeList
simple in browsers that don't supportNodeList.prototype.forEach
, so it's best to do:forEach(document.querySelectorAll('.my-component'), (el, idx) => { .. });