Created — forked from 140bytes/LICENSE.txt

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

polyfill an ES5-compatibile Object.keys where needed.

View LICENSE.txt
1 2 3 4 5 6 7 8 9 10 11 12 13
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
 
Copyright (C) 2011 Alex Kloss <alexthkloss@web.de>
 
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.
View LICENSE.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Object.keys = Object.keys ||
function (
o, // object
k, // key
r // result array
){
// initialize object and result
r=[];
// iterate over object keys
for (k in o)
// fill result array with non-prototypical keys
r.hasOwnProperty.call(o, k) && r.push(k);
// return result
return r
}
View LICENSE.txt
1
Object.keys=Object.keys||function(o,k,r){r=[];for(k in o)r.hasOwnProperty.call(o,k)&&r.push(k);return r}
View LICENSE.txt
1 2 3 4 5 6 7 8 9 10 11 12
{
"name": "objkeys",
 
"description": "polyfill an ES5-compatibile Object.keys where needed.",
 
"keywords": [
"object",
"keys",
"es5",
"polyfill"
]
}
View LICENSE.txt
1 2 3 4 5 6 7 8 9 10 11
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>test, a, b, c</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var testdata = { test: 1, a: 2, b: 3, c: 4 };
var keys = Object.keys=Object.keys||function(o,k,r){r=[];for(k in o)r.hasOwnProperty.call(o,k)&&r.push(k);return r}
document.getElementById( "ret" ).innerHTML = keys(testdata);
</script>

There is no Object.prototype.keys in ES5 ;)

/edit:
You code fails for: {hasOwnProperty:3}

Owner
atk commented

Sorry, got carried away by the Array stuff; hasOwnProperty is usually a prototypical method of Object, so setting it is usually a somewhat stupid idea (like naming an form input "action" or "submit". Anyway, one could use r.hasOwnProperty.call(o,k) to take care of this.

jed commented

hey @atk, would you mind taking the trailing comma out of your package.json keywords?

Owner
atk commented

Not at all (same for the other gists) :)

To be ES5 compatible it would also need to throw an error when o is not an object/function.

Object.keys=Object.keys||function(o,r){r=[];for(r[r.length] in o);return r}

for(r[r.length] in o); - this is Beautiful! but we have to use hasOwnProperty...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.