DEV Community

Cover image for Post an Elegant Code Snippet You Love.

Post an Elegant Code Snippet You Love.

dev.to staff on August 31, 2023

Step into our coding showcase series, where you can elevate your projects, exhibit your coding prowess, and collaborate with like-minded developers...
Collapse
 
luizgtvsilva profile image
Luiz Gustavo da Silva • Edited

Using this:

new_list = [x for x in old_list if x > 0]
Enter fullscreen mode Exit fullscreen mode

Instead of this:

new_list = []
for x in old_list:
    if x > 0:
        new_list.append(x)
Enter fullscreen mode Exit fullscreen mode

It's so beautiful hahaha

Collapse
 
somedood profile image
Basti Ortiz

I've always loved the one-liner for summing up an array of numbers in JavaScript. A lot of people take a hard line on reduce, but I think it looks really nice here.

const sum = numbers.reduce((total, curr) => total + curr);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
franklivania profile image
Chibuzo Franklin Odigbo

One liners are the absolute best!

Collapse
 
richardj profile image
R☭ • Edited

Toggling by using:

variable = !variable;
Enter fullscreen mode Exit fullscreen mode

has to be one of my favorites.

Collapse
 
ben profile image
Ben Halpern

I think pulling from arrays with some filters in Ruby is nice, such as

[1, 2, 3, 4, 2, 3, 1, 3, 4, 5].uniq.compact.select(&:even?)
Enter fullscreen mode Exit fullscreen mode

uniq removes dupes and compact removes nil and .select(&:even?) will limit the output to even numbers.

Collapse
 
calinzbaenen profile image
Calin Baenen • Edited

what is the syntax &:even??

Collapse
 
edwardloveall profile image
Edward Loveall • Edited

I've heard it called a "symbol to proc" or "symbol proc" and it's short for this:

.select { |foo| foo.even? }
# same as 
.select(&:even?)
Enter fullscreen mode Exit fullscreen mode

It's calling the method even? on each number passed in. Behind the scenes it creates a proc and then passes in each number. Here are the ruby docs for Symbol#to_proc and here's a pretty decent break down of symbol to proc.

Collapse
 
tqbit profile image
tq-bit • Edited

I find using nested hashmaps instead of if-else statements rather elegant when running decision based flows.

I've recently refactored a codebase with a lot of nested if-else control flows using this method. Said project is now much easier to read since decision logic is abstracted from the function using it.

What I also like is that it's easier to type your decision map with jsdoc or ts.

Example

const sequenceMap = Object.freeze({
  admin: {
    authorized: {
        action: () => console.log("Logged in as admin")
    }, 
    notAuthorized: {
        action: () => console.log("Could not login admin!")
    }
  },
  user: {
    authorized: {
        action: () => console.log("Logged in as user")
    }, 
    notAuthorized: {
        action: () => console.log("Could not login user!")
    }
  }
});

const runSequenceAction = (role, auth) => {
    return sequenceMap[role][auth].action();
}

runSequenceAction('admin', 'authorized');
Enter fullscreen mode Exit fullscreen mode

Same functionality with if-else

function runAuthAction(role, auth) {
  if(role === "admin") {
    if(auth === "authorized") {
        console.log("Logged in as admin");
    } else if (auth === "unauthorized") {
        console.log("Could not login admin!")
    }
  } else if (role === "user") {
    if(auth === "authorized") {
        console.log("Logged in as user");
    } else if (auth === "unauthorized") {
        console.log("Could not login user")
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
eliasjsalves profile image
eliasjsalves

Fast inverse square root, the function that revolutionized 3D games industry:

float Q_rsqrt(float number) {
     long i;
     float x2, y;
     const float threehalfs = 1.5F;
     x2 = number * 0.5F;
     y  = number;
     i  = * (long *) &y;  //evil floating point bit lvl hacking
     i  = 0x5f3759df - ( i >> 1 ); // what the fuck?
     y  = * (float *) &i;
     y  = y * (threehalfs - (x2 * y * y));  
     return y;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
moopet profile image
Ben Sinclair

It's cool, but I wouldn't ever call it "elegant"!

Collapse
 
oleksii profile image
Alexey

I didn't get a damn thing, but that one is just beautiful

Collapse
 
franklivania profile image
Chibuzo Franklin Odigbo

This is my best code snippet yet. It does exactly what you see it does

export default function PageToggle({className, title, image, link}: PageTypes) {
    const location = useLocation()
    const isActive:boolean = location.pathname === link 

    function handleClick() {
        window.location.href = link
    }
    return(
        <PageButton
            type='button'
            className={`${className} ${isActive ? 'active' : ''}`}
            onClick={handleClick}
        >
            {image && <img src={image} alt="" />}
            {title}
        </PageButton>
    )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ryencode profile image
Ryan Brown

Duff's Device

send(to, from, count)
register short *to, *from;
register count;
{
    do {                          /* count > 0 assumed */
        *to = *from++;
    } while (--count > 0);
}
Enter fullscreen mode Exit fullscreen mode

From Duff's device

The unroll with uneven ending version is a thing of beauty:

send(to, from, count)
register short *to, *from;
register count;
{
    register n = (count + 7) / 8;
    switch (count % 8) {
    case 0: do { *to = *from++;
    case 7:      *to = *from++;
    case 6:      *to = *from++;
    case 5:      *to = *from++;
    case 4:      *to = *from++;
    case 3:      *to = *from++;
    case 2:      *to = *from++;
    case 1:      *to = *from++;
            } while (--n > 0);
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nickytonline profile image
Nick Taylor • Edited

I find this super handy if you’re building DOM elements without a framework.

Collapse
 
efpage profile image
Eckehard • Edited

I like the way you handle the props in your function, I just would prefer to immediately add some content to the new element. I slightly extended your function to add some content (a text, a child node or an array of child nodes)

function createElement(nodeName, content , props = {}) {
    const { style = {}, ...propsNoStyle } = props;
    const element = Object.assign(document.createElement(nodeName), propsNoStyle);
    Object.entries(style).forEach(([key, value]) => { element.style[key] = value; });

    // append child or array of childs
    function append(cl) { 
        if (typeof (cl) === 'string') cl = document.createTextNode(cl)
        element.appendChild(cl)
    }
    if (Array.isArray(content)) content.map(cl => append(cl))
    else append(content)

    return element;
}
Enter fullscreen mode Exit fullscreen mode

There is a really tricky pattern to build "creator" functions for DOM elements based on your function (thanks to Tao from VanJS) :

makefnc = function (typ) {
    return (...args) =>
        createElement(typ, ...args)
}

tags = new Proxy({}, { 
    get: (tag, name) => {
        return makefnc(name)
    }
})
Enter fullscreen mode Exit fullscreen mode

The code above could be written more compact, but this makes it really hard to understand. makefnc returns a function that creates a special type of element. You can use it that way:

const h1 = makefnc("h1")
let el = h1("This is a headline", {style: {color: "red"}})
Enter fullscreen mode Exit fullscreen mode

Using the tags function is even more elegant. Below, I show a little code example:

const { div, h1, button } = tags // create tag functions for div, h1 and button

let h, b, count = 0
h = h1(`${count}`, { style: { color: "red" } });
(b = button("CLICK")).onclick = () => h.innerText = ++count

document.body.append(div([h, b]))
Enter fullscreen mode Exit fullscreen mode

There is an even more compact approach on the same principle presented here, that adds an auto-append feature, so you do not even need to append the elements manually.

Collapse
 
nickytonline profile image
Nick Taylor

I didn’t bother with the content as you can just add a prop textContent or similar, but glad to see you’re extending it!

Thread Thread
 
efpage profile image
Eckehard

Sure, in that case it's just a question of convenience. But you can also build nested elements, so it´s a way to compose your page or parts of it :

        let d, h, b, count = 0
        d = div([
            h = h1(`${count}`, { style: { color: "red" } }),
            b = button("CLICK")
        ])
        b.onclick = () => h.innerText = ++count
        document.body.append(d)
Enter fullscreen mode Exit fullscreen mode

By the way, CSS styles use a syntax, which is a bit different from JSON:

<p style="color:blue;font-size:46px;">
Enter fullscreen mode Exit fullscreen mode

With your approach, people need to translate the style definition like this:

 createElement("p",{style: {color:"blue";font-size:"46px;"})
Enter fullscreen mode Exit fullscreen mode

As you need to process the styles anyway, would it not be better to use the usual syntax?

 createElement("p",{style: "color:blue;font-size:46px;")
Enter fullscreen mode Exit fullscreen mode

If you do not want to process the CSS manually, you can use this function:

function setStyle(el, css){
  el.setAttribute('style', el.getAttribute('style') + ';' + css);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
godot profile image
Godot

Perhaps I'm the one here that post non brackets-semicolon snippets, It's GDScript. But here you go

class_name Player extends Node2D

var health := 100

func _ready():
    pass

func take_damage(damage_amount):
    health -= damage_amount
    if health <= 0:
        die()

func die():
    # Implement player death logic here
    queue_free()  # Destroy the player node

Enter fullscreen mode Exit fullscreen mode
Collapse
 
chantal profile image
Chantal

Reversing a string in Javascript looks super simple and easy to me since day one. You could reverse a string in Javascript using a reverse for loop, but we can utilize the powerfull built-in Array methods reverse() and join() to create a one-liner that does the same thing.

const reverseString = (str) => str.split('').reverse().join('');
const reverse = reverseString('javascript');
console.log(reverse); // tpircsavaj
Enter fullscreen mode Exit fullscreen mode
Collapse
 
benborla29 profile image
Ben Borla

In Laravel I learned something by accident. I was trying to retrieve the roles of the user using this Query Builder.

User::find(1)->rolesPivot()->get()->pluck(‘roles’)->implode(‘, ’);

This outputs (example value only)
Admin, Reporter, Staff

Collapse
 
thesmarthyena profile image
Philippe Skopal

Or this implementation of the Observer Design pattern in react.

import React, { useEffect, useReducer, createContext, useContext } from "react";
import "./styles.css";

const initialState = { trigger: 0, text: "", timestampedText: "" };

function reducer(state, action) {
  switch (action.type) {
    case "trigger":
      return { ...state, trigger: state.trigger + 1 };
    case "updateText":
      return { ...state, text: action.newValue, trigger: state.trigger + 1 };
    case "updateTimestampedText":
      return { ...state, timestampedText: action.newValue };
    default:
      return state;
  }
}

const StateContext = createContext(null);

const useStore = () => {
  return useContext(StateContext);
};

const TriggerListenerComponent = () => {
  const [state, dispatch] = useStore();

  useEffect(() => {
    dispatch({
      type: "updateTimestampedText",
      newValue: `${Date.now()} - ${state.text}`
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.trigger]);

  return <></>;
};

const Body = () => {
  const [state, dispatch] = useStore();

  const handleChange = (event) => {
    dispatch({ type: "updateText", newValue: event.target.value });
  };

  const handleClick = () => {
    dispatch({ type: "trigger" });
  };

  return (
    <>
      <div className="App">
        <p>
          Change the input to observe how the trigger works and can be used.
        </p>

        <p>
          Click to refresh manually the timestamped value (without changing the
          text).
        </p>
        <button onClick={handleClick}>Trigger</button>
        <br />
        <br />
        <input value={state.text} onChange={handleChange} />
        <br />
        <p> Unique timestamped text: {state.timestampedText} </p>
      </div>
      <TriggerListenerComponent />
    </>
  );
};

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <StateContext.Provider value={[state, dispatch]}>
      <Body />
    </StateContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
thesmarthyena profile image
Philippe Skopal

I found a simple way, to overcome the context limitation of a setInterval.
Demo here: codesandbox.io/s/demosetintervalco...

import React, { useEffect, useState, useReducer } from "react";
import "./styles.css";

const initialState = { count: 0 };

// The reducer function
function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    default:
      return { count: state.count };
  }
}

export default function App() {
  const [count, setCount] = useState(0);
  const [state, dispatch] = useReducer(reducer, initialState);

  useEffect(() => {
    const interval = setInterval(() => {
      setCount(count + 1);
      dispatch({ type: "increment" });
      console.log("Count no reducer:", count);
      console.log("Count with reducer: ", state.count);
    }, 1000);
    return () => clearInterval(interval);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="App">
      <h1>Count no reducer: {count}</h1>
      <h1>Count with reducer: {state.count}</h1>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Without this pattern, the context value never changes.

Collapse
 
blossom profile image
Blossom Babs

Still cannot get over how simplified handling click event is in javascript

const handleMobileNav = () => setIsMobile(!isMobile)
Enter fullscreen mode Exit fullscreen mode