Skip to content

Instantly share code, notes, and snippets.

@bitifet
Last active January 25, 2024 16:22
Show Gist options
  • Save bitifet/2466e5ce39eef2829fd03990e04fef11 to your computer and use it in GitHub Desktop.
Save bitifet/2466e5ce39eef2829fd03990e04fef11 to your computer and use it in GitHub Desktop.
objectMap(): Kind of Array.map() but for objects...
// USAGE: objectMap(<object>, <callback>)
// <object>: Any regular JavaScript object.
// <callback>: function(<current_value>, <current_key>, <original_object>) {...}
// EXAMPLE:
// objectMap({a: null, b: "23"}, Number) //-> { a: 0, b: 23 }
function objectMap(obj, cbk) {
return Object.fromEntries(
Object.entries(obj).map(
([key, value])=>[key, cbk(value, key, obj)]
)
);
};
// Object enhancer adding methods that work like objectMap, but chainable.
// USAGE: enhancedObject = O(originalObject);
// EXAMPLE:
// const myObj = O({foo: 2, bar: 1, baz: 0});
// myObj
// .filter(v=>!!v) // {foo: 2, bar: 1}
// .toKeySorted() // {bar: 1, foo: 2}
// .toSorted((a,b)=>b-a) // {foo: 2, bar: 1}
// .map(String) // {foo: "2", bar: "1"}
// ;
const oParse = (obj, parser) => Object.fromEntries(parser(Object.entries(obj)));
class O extends Object {
constructor(src, ...args) {
super(...args);
Object.assign(this, src);
};
map(cbk){
return new O(oParse(this
, entries=>entries.map(([key, value])=>[key, cbk(value, key, this)])
));
};
filter(cbk){
return new O(oParse(this
, entries=>entries.filter(([key, value])=>!!cbk(value, key, this))
));
};
toSorted(cbk=(a,b)=>(a<b?-1:a>b?1:0)){
return new O(oParse(this
, entries=>entries.sort(([,v1], [,v2])=>cbk(v1, v2))
));
};
toKeySorted(cbk=(a,b)=>(a<b?-1:a>b?1:0)){
return new O(oParse(this
, entries=>entries.sort(([k1], [k2])=>cbk(k1, k2))
));
};
};
export const O = o=>new O(o);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment