There have been multiple accounts created with the sole purpose of posting advertisement posts or replies containing unsolicited advertising.

Accounts which solely post advertisements, or persistently post them may be terminated.

frezik ,

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.


<span style="color:#323232;">function generate_class_name( display_type, size, bordered, class_name_prop ) 
</span><span style="color:#323232;">{
</span><span style="color:#323232;">  classes = [
</span><span style="color:#323232;">      'btn',
</span><span style="color:#323232;">      ( display_type ? display_type : [] ),
</span><span style="color:#323232;">      ( size ? size : [] ),
</span><span style="color:#323232;">      ( bordered ? bordered : [] ),
</span><span style="color:#323232;">      ( class_name_prop ? class_name_prop : [] ),
</span><span style="color:#323232;">  ];
</span><span style="color:#323232;">
</span><span style="color:#323232;">  return classes.flat().join( " " );
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">console.log( "<"
</span><span style="color:#323232;">    + generate_class_name( "mobile", "big", null, null )
</span><span style="color:#323232;">    + ">" );
</span><span style="color:#323232;">console.log( "<"
</span><span style="color:#323232;">    + generate_class_name( "desktop", "small", "solid", "my-class" ) 
</span><span style="color:#323232;">    + ">" );
</span><span style="color:#323232;">console.log( "<"
</span><span style="color:#323232;">    + generate_class_name( null, "medium", null, null ) 
</span><span style="color:#323232;">    + ">" );
</span>

Results:


<span style="color:#323232;"><btn mobile big>
</span><span style="color:#323232;"><btn desktop small solid my-class>
</span><span style="color:#323232;"><btn medium>
</span>

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.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • [email protected]
  • random
  • lifeLocal
  • goranko
  • All magazines