Created
April 24, 2022 03:33
-
-
Save nberlette/8f55e573c57a94c96c585f130fd18685 to your computer and use it in GitHub Desktop.
This file contains hidden or 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