Last active
July 20, 2021 18:56
-
-
Save belden/9d39a9d5b10c43c5713d549ee0949a24 to your computer and use it in GitHub Desktop.
overEach - apply a function over each key of an object, or just get all its keys safely
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
var pojo = { | |
foo: 'bar', | |
baz: 'qux' | |
}; | |
var ownKeys = function () { | |
return Object.keys(this).filter(function(k) { | |
return this.hasOwnProperty(k); | |
}, this); | |
}; | |
// overEach(fn: (key: String, value: Object, context: Object, tuple: {<String>: <Object>}), [Object]) : Array | |
// overEach(): [<String>, ...] | |
var overEach = function (fn, context) { | |
var keys = this.ownKeys(); | |
if (! fn) return keys; | |
var arity = fn.length; | |
return keys.map(function(k) { | |
var tuple = {}; | |
tuple[k] = this[k]; | |
var args = [k, this[k], this, tuple]; | |
return fn.apply(context || this, args.slice(0, arity)); | |
}, this); | |
}; | |
Object.prototype.overEach = overEach; | |
pojo.overEach = overEach; | |
// apply a function | |
var mojo = 'mojo'; | |
var tuples = pojo.overEach(function (k, v, o, t) { | |
console.log(`${this}: ${k} => ${v}`); | |
return t; | |
}, mojo).map(function (o) { | |
return o.overEach(function(k, v) { | |
console.log(`nested obj: ${k} => ${v}`); | |
return [k, v]; | |
}); | |
}); | |
console.log(tuples); | |
// just give me the keys | |
console.log(pojo.overEach()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I can't remember why I wrote this.