Last active
January 25, 2024 16:22
Revisions
-
bitifet revised this gist
Jan 25, 2024 . 1 changed file with 39 additions and 0 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,39 @@ // 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); -
bitifet created this gist
Jan 24, 2024 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,12 @@ // 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)] ) ); };