Skip to content

Instantly share code, notes, and snippets.

@defims
Forked from Golmote/LICENSE.txt
Last active June 14, 2016 01:28
Show Gist options
  • Save defims/be63dcabfbfa088960c96eb91bfa25eb to your computer and use it in GitHub Desktop.
Save defims/be63dcabfbfa088960c96eb91bfa25eb to your computer and use it in GitHub Desktop.
Looping function for Array, Objects and Array-Like
function(
a, // Objet or Array to loop into
b, // Function to execute for each element
c, // Boolean to force "Object" behaviour
d, // Placeholders
e
){
if(
c // If the "Object" loop is forced
||
(c=a.length) == e // or if there's not any "length" property (let's store it)
)
for(d in a) // for/in loop
a.hasOwnProperty(d) // with hasOwnProperty check
&&
b.call(e=a[d],d,e,a); // Call the function as a method of the item
else
for(d=0;d<c;) // else classic loop
b.call(e=a[d],d++,e,a) // Call the function as a method of the item
}
export function(a,b,c,d,e){if(c||(c=a.length)==e)for(d in a)a.hasOwnProperty(d)&&b.call(e=a[d],d,e,a);else for(d=0;d<c;)b.call(e=a[d],d++,e,a)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "loopThemAll",
"description": "Function for looping through Arrays, Objects and Array-Like Objects",
"keywords": [ "loop", "array", "objects", "array-like" ],
"version": "0.1.0"
}
<!DOCTYPE html>
<html>
<head>
<title>Loop'em all - 136 chars</title>
</head>
<body>
<div>Expected value:<br />
<b>
Array : 0 -> zero, 1 -> one, 2 -> two, <br />
Object : prop -> value, prop2 -> 154.4, <br />
Array-Like : 0 -> zero, 1 -> one, <br />
Array-Like forced as object : 0 -> zero, 1 -> one, length -> 2,
</b>
</div>
<div>Actual value:<br /> <b id="ret"></b></div>
<script>
var each = function(a,b,c,d,e){if(c||(c=a.length)==e)for(d in a)a.hasOwnProperty(d)&&b.call(e=a[d],d,e,a);else for(d=0;d<c;)b.call(e=a[d],d++,e,a)},
f = function(i, v) {
str += i + ' -> ' + v + ', ';
},
str = 'Array : ';
each(['zero', 'one', 'two'], f);
str += '<br />Object : ';
each({prop: 'value', prop2: 154.4}, f);
str += '<br />Array-Like : ';
each({0: 'zero', 1: 'one', length: 2}, f);
str += '<br />Array-Like forced as object : ';
each({0: 'zero', 1: 'one', length: 2}, f, true);
document.getElementById('ret').innerHTML = str;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment