• itsnotlupus@lemmy.world
    link
    fedilink
    arrow-up
    22
    ·
    edit-2
    1 year ago

    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.

    • aidan@lemmy.world
      link
      fedilink
      arrow-up
      3
      ·
      1 year ago

      Reminds me when my I did all my homework using list comprehension, ternary operations, and lambda expressions because it was boring. Here’s an example

      def task03( matrix ):
          print((new_matrix := [[ (y if y != 0 else ( temp := sum([r[j] for r in matrix[0:i]] + x[j:]), zeros_sum := (zeros_sum if 'zeros_sum' in locals() else 0) + temp)[0] ) for j,y in enumerate(x)] for i,x in enumerate(matrix)], '\n'.join( [ ' '.join([str(new_matrix[o][p]) for p in range(0 if len(matrix[0]) <= 20 else len(matrix[0])-20, len(matrix[0]))]) for o in range(0 if len(matrix) <= 20 else len(matrix)-20, len(matrix))  ] ) + '\n' + str(zeros_sum) )[1] )