Skip to content

Instantly share code, notes, and snippets.

@belden
Last active July 20, 2021 18:56
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 belden/9d39a9d5b10c43c5713d549ee0949a24 to your computer and use it in GitHub Desktop.
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
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());
@belden
Copy link
Author

belden commented Jul 20, 2021

I can't remember why I wrote this.

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