Skip to content

Instantly share code, notes, and snippets.

@unphased
Last active February 6, 2016 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unphased/64496b7f93e58acc5cc4 to your computer and use it in GitHub Desktop.
Save unphased/64496b7f93e58acc5cc4 to your computer and use it in GitHub Desktop.
function mapObj(obj, cb) {
var mappedObject = null;
var mappedArray = Object.keys(obj).map(function(e, i, a) {
var mapped = cb(e, obj[e], i);
if (mappedObject !== false && Array.isArray(mapped) && mapped.length === 2) {
if (!mappedObject) {
mappedObject = { };
}
mappedObject[mapped[0]] = mapped[1];
// always do the work of normal array mapping, I guess
} else { // any instance of non object-map response aborts assembly of mappedObject
if (mappedObject) { // not false and not null, therefore is object
// here is where we might implement going back to re-assemble·
// mappedObject into mappedArray but we're actually always·
// building mappedArray so for now we must do exactly nothing
}
mappedObject = false;
}
return mapped;
});
return mappedObject || mappedArray;
}
// a scary thing, albeit with effort expended to make it "safe" with
// a overwrite-check.
if (!Object.prototype.map) {
Object.defineProperty(Object.prototype, 'map', {
value: function(cb) {
return mapObj(this, cb);
},
writable: true,
configurable: true,
enumerable: false
});
}
var test = function () {
somevar = {method:'value', blargle: 325234, 34234: 222};
console.log(JSON.stringify(somevar.map(function(k,v){ return {key: k, val: v} })));
console.log(JSON.stringify(somevar.map(function(k,v){ return ['map'+k, v+'map'] })));
// You shall expect:
// [{"key":"34234","val":222},{"key":"method","val":"value"},{"key":"blargle","val":325234}]
// {"map34234":"222map","mapmethod":"valuemap","mapblargle":"325234map"}
}
@unphased
Copy link
Author

unphased commented Feb 6, 2016

This has mysterious, deleterious side effects. For example, my three.js app happens to die inside of WebGL uniform binding routines. Take this code back out, and it doesn't happen. So it would be cool to investigate that at some point to pick apart what weirdness is going on there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment