• 0 Posts
  • 3 Comments
Joined 1 year ago
cake
Cake day: June 24th, 2023

help-circle


  • One of my guilty pleasures is to rewrite trivial functions to be statements free.

    Since I’d be too self-conscious to put those in a PR, I keep those mostly to myself.

    For example, here’s an XPath wrapper:

    const $$$ = (q,d=document,x=d.evaluate(q,d),a=[],n=x.iterateNext()) => n ? (a.push(n), $$$(q,d,x,a)) : a;
    

    Which you can use as $$$("//*[contains(@class, 'post-')]//*[text()[contains(.,'fedilink')]]/../../..") to get an array of matching nodes.

    If I was paid to write this, it’d probably look like this instead:

    function queryAllXPath(query, doc = document) {
        const array = [];
        const result = doc.evaluate(query, doc);
        let node= result.iterateNext();
        while (node) {
            array.push(node);
            n = result.iterateNext();
        }
        return array;
    }
    

    Seriously boring stuff.

    Anyway, since var/let/const are statements, I have no choice but to use optional parameters instead, and since loops are statements as well, recursion saves the day.

    Would my quality of life improve if the lambda body could be written as => if n then a.push(n), $$$(q,d,x,a) else a ? Obviously, yes.