Skip to content

Instantly share code, notes, and snippets.

@MKRhere
Last active December 12, 2018 08:04
Show Gist options
  • Save MKRhere/2d3724420c177113e3903476cbfd6f8c to your computer and use it in GitHub Desktop.
Save MKRhere/2d3724420c177113e3903476cbfd6f8c to your computer and use it in GitHub Desktop.
Object.prototype extensions for JavaScript
Object.prototype[Symbol.iterator] = function () {
let i = 0;
const keys = Object.keys(this);
return {
next: () => {
return {
value: [keys[i], this[keys[i++]]],
done: i > keys.length,
};
},
};
};
Object.prototype.reduce = function (reducer, init) {
let acc = init;
for (const [key, value] of this) {
acc = reducer(acc, value, key, this);
}
return acc;
};
Object.prototype.map = function (mapper) {
return this.reduce((acc, value, key) => {
acc[key] = mapper(value, key, this);
return acc;
}, {});
};
Object.prototype.filter = function (pred) {
return this.reduce((acc, value, key) => {
if (pred(value, key, this))
acc[key] = value;
return acc;
}, {});
};
Object.prototype.find = function (pred) {
for (const [key, value] of this) {
if (pred(value, key, this)) return value;
}
};
Object.prototype.findKey = function (pred) {
for (const [key, value] of this) {
if (pred(value, key, this)) return key;
}
};
Object.prototype.findPair = function (pred) {
for (const [key, value] of this) {
if (pred(value, key, this)) return [key, value];
}
};
const obj = { a: 10, b: 20 };
for (const item of obj) {
console.log(item);
// [ "a", 10 ]
// [ "b", 20 ]
}
console.log(obj.map(x => x * 2)); // { a: 20, b: 40 }
console.log(obj.filter(x => x > 10)); // { b: 20 }
console.log(obj.find(x => x > 10)); // 20
console.log(obj.findKey(x => x > 10)); // 'b'
console.log(obj.findPair(x => x > 10)); // [ 'b', 20 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment