this post was submitted on 21 Mar 2024
293 points (94.8% liked)

Programmer Humor

19176 readers
1688 users here now

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

founded 1 year ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[โ€“] frezik@midwest.social 1 points 5 months ago* (last edited 5 months ago) (1 children)

I'd say this example doesn't fully show off what immutable data can do--it tends to help as things scale up to much larger code--but here's how I might do it in JS.

function generate_class_name( display_type, size, bordered, class_name_prop ) 
{
  classes = [
      'btn',
      ( display_type ? display_type : [] ),
      ( size ? size : [] ),
      ( bordered ? bordered : [] ),
      ( class_name_prop ? class_name_prop : [] ),
  ];

  return classes.flat().join( " " );
}

console.log( "<"
    + generate_class_name( "mobile", "big", null, null )
    + ">" );
console.log( "<"
    + generate_class_name( "desktop", "small", "solid", "my-class" ) 
    + ">" );
console.log( "<"
    + generate_class_name( null, "medium", null, null ) 
    + ">" );

Results:

<btn mobile big>
<btn desktop small solid my-class>
<btn medium>

Notice that JavaScript has a bit of the immutability idea built in here. The Array.flat() returns a new array with flattened elements. That means we can chain the call to Array.join( " " ). The classes array is never modified, and we could keep using it as it was. Unfortunately, JavaScript doesn't always do that; push() and pop() modify the array in place.

This particular example would show off its power a little more if there wasn't that initial btn class always there. Then you would end up with a leading space in your example, but handling it as an array this way avoids the problem.

[โ€“] madcaesar@lemmy.world 2 points 5 months ago

Very interesting. Actually the part you mention about there being an initial 'btn' class is a good point. Using arrays and joining would be nice for that. I wish more people would chime in. Because between our two examples, I think mine is more readable. But yours would probably scale better. I also wonder about the performance implications of creating arrays. But that might be negligible.