DEV Community

Itachi Uchiha
Itachi Uchiha

Posted on

What code snippets do you use?

Hi. Sometimes, we create code snippets to help us. In a project, I needed to create an element and its attributes should have been set. I wasn't using jQuery or like libraries. I've created a JavaScript function like that.

const element = (data) => {
    const el = document.createElement(data["tag"])

    if(data["type"]) {
        el["type"] = data["type"]
    }

    if(data["id"]) {
        el["id"] = data["id"]
    }

    if(data["class"]) {
        const classList = data["class"]

        classList.map(m => {
            el.classList.add(m)
        })
    }

    if(data["text"]) {
        el["textContent"] = data["text"]
    }

    if(data["html"]) {
        el["innerHTML"] = data["html"]
    }

    if(data["attr"]) {
        const attr = data["attr"]
        const keys = Object.keys(data["attr"])

        keys.map(m => {
            el.setAttribute(m, attr[m])
        })
    }

    if(data["event"]) {
        const attr = data["event"]
        const keys = Object.keys(data["event"])

        keys.map(m => {
            const eventName = "on" + m
            el.setAttribute(eventName, attr[m])
        })
    }

    if(data["addTo"]) {
        const target = document.querySelectorAll(data["addTo"])

        target.forEach((m, i) => {
            m.appendChild(el)
        })
    }

    if(data["style"]) {
        const attr = data["style"]
        const keys = Object.keys(data["style"])
        let styleCode = '';
        keys.map(m => {
            const props = attr[m]
            const prop_keys = Object.keys(attr[m])

            styleCode += `${m} {`

            prop_keys.map(p => {
                styleCode += `${p}:${props[p]};`
            })

            styleCode += '}'
        })

        const style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = styleCode;
        document.getElementsByTagName('head')[0].appendChild(style);
    }

    return el
}
Enter fullscreen mode Exit fullscreen mode

This function always works for me. If you want to use this function you can use like this;

// Example Usage

element({
    'tag': 'button',
    'type': 'button',
    'addTo': '.test-body',
    'html': '<img src="https://cdn-images-1.medium.com/max/2000/0*uORWkYMjiF3LA-K8" />', // or text
    'id': 'user-card',
    'class': ['profile-link', 'avatar'],
    'attr': {
        'name': 'user-name',
        'value': 'Ali',
        'data-id': 1,
        'data-path': '/profile/1'
    },
    'event': {
        "click": `console.log(123)`
    },
    'style': {
        '.profile-link': {
            "color": "#fff",
            "background-color": "#000"
        },
        ".profile-link:hover": {
            "color": "#000",
            "background-color": "#fff",
            "border": "1px dashed #000;"
        },
        ".avatar": {
            "width": "300px",
            "height": "300px",
            "border": "1px dashed #e3e3e3;"
        },
        ".avatar img": {
            "width": "285px",
            "height": "285px"
        }
    }
})
Enter fullscreen mode Exit fullscreen mode

Check it on the CodePen

Anyway, I wonder, what code snippets do you use?

Top comments (15)

Collapse
 
aalises profile image
Albert Alises

Specially for testing with Puppeteer I have some common functions that I reuse in most of the tests like login() or navigateToProject() or util functions to get properties from selectors, etc...

Collapse
 
laviku profile image
Lavinia

This is silly but I have a code snippet of htaccess to improve wordpress performance. It's just that my brain has never understood Regex :/
I also have code snippets for validations and other little things in vanilla javascript.

Collapse
 
tux0r profile image
tux0r

I have no common "framework" for my projects as they all differ from each other too much. Sometimes I reuse certain code parts, especially in C, e.g. for accessing the file system. But that's always an exception.

Collapse
 
itachiuchiha profile image
Itachi Uchiha

What kind of codes? But I understand you. Sometimes you don't want to spend more times because of the same problems.

Collapse
 
tux0r profile image
tux0r

e.g. for accessing the file system

:)

Collapse
 
scottishross profile image
Ross Henderson

We have a few templates we use, and some reusable code snippets.

Stuff like:

Email Validations

case 
   when regexp_like(CUSTOMER_EMAIL_ADDRESS, '^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*@[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*\.([a-z]{2,4})$') 
   then CUSTOMER_EMAIL_ADDRESS
   else null 
end as "EMAIL_ADDRESS"

Randomise Date Column

update
 TABLE
set
  DATE_COLUMN = TO_DATE(TRUNC(DBMS_RANDOM.value(TO_CHAR(date '2018-03-06','J'),TO_CHAR(CURRENT_TIMESTAMP,'J'))),'J');

Etc...

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

I've had a discussion about snippets on here somewhere before. But for me and my programming style, I view code snippets as a horror. I can see that they would be useful for some cases, but those are cases I tend to avoid. What I often do is to create types and functions to encapsulate some code, put it in a library, and then reuse it in different projects.

Collapse
 
qm3ster profile image
Mihail Malo

Any reason you are using string index notation (data["addTo"]) and not dot notation (data.addTo)?

Collapse
 
itachiuchiha profile image
Itachi Uchiha

For example, I could have a key like that;

myObject['userName[]']

In this case, I can't use like that myObject.userName[]

There are many reasons to use index notation.

medium.com/@prufrock123/js-dot-not...

Collapse
 
qm3ster profile image
Mihail Malo

Yeah, but you don't.
There are many reasons not to, as well.

Collapse
 
nektro profile image
Meghan (she/her)

I use them so often I made my own library (github.com/nektro/basalt)

In particular of note, I have (github.com/nektro/basalt/blob/mast...)

Collapse
 
itachiuchiha profile image
Itachi Uchiha

This looks much better and cleaner.

Collapse
 
bgadrian profile image
Adrian B.G.

"The ones that do no use frameworks, end up making their own square wheel".

You should not have many snippets between projects, engines, frameworks and shared libs yes.

Collapse
 
sagar profile image
Sagar

clg => console.log()

Collapse
 
d1p profile image
Debashis Dip

I do have some common nginx config file suited for my projects, and some general python util functions that i need here and there