Skip to content

Instantly share code, notes, and snippets.

@bitifet
Last active January 25, 2024 16:22

Revisions

  1. bitifet revised this gist Jan 25, 2024. 1 changed file with 39 additions and 0 deletions.
    39 changes: 39 additions & 0 deletions objectWrapper.js
    Original 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);
  2. bitifet created this gist Jan 24, 2024.
    12 changes: 12 additions & 0 deletions objectMap.js
    Original 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)]
    )
    );
    };