Code snippets for your daily life

Find useful snippets, bookmark and share them with other developers.

Latest Snippets

  • const user = {
      id: 42,
      name: 'Son Goku',
      email: 'son@goku.db'
    }
    
    for(const prop in user) {
      console.log(`${prop}: ${user[prop]}`)
    }
    
    /*
    output:
    'id: 42'
    'name: Son Goku'
    'email: son@goku.db'
    */
    Copy

    August 1st, 2021

    # for...in - Looping an object

    Add to bookmarks

    prop isn't a property, but the string representation of the property key. This way we're able to acces the property value by usering the bracket notion user[prop].

    This loop can be applied on arrays, because they are literally objects, but it's not recommended. The right order can't be guaranteed.

  • // the magical function
    async function promiseHandler(promise) {
      try {
        const data = await promise;
        return [data, null]
      } catch(error) {
        console.error(error);
        return [null, error]
      }
    }
    
    const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('Resolve')
      }, 1000)
    })
    
    const getDataFromAPI = async () => {
      const [data, error] = await promiseHandler(promise)
    
      // output: 'data' 'Resolve'
      console.log('data', data)
    
      // output: 'error' null
      console.log('error', error)
    }
    
    getDataFromAPI()
    Copy

    June 17th, 2021

    # Simple way to handle promises

    Add to bookmarks

    To avoid stuffing our functions with try-catch blocks when working with asynchronous code, we use a function (promiseHandler()) which always returns an array containing the data for a resolved or the error for a rejected promise.

  • function flattenObject(objectTree) {
      const flatObject = {};
    
      if (!objectTree) {
        return flatObject;
      }
    
      Object.keys(objectTree).forEach((rootKey) => {
        if (Object.prototype.hasOwnProperty.call(objectTree, rootKey)) {
          // flatten deep nested objects
          if (typeof objectTree[rootKey] === 'object') {
            const deepObject = flattenObject(objectTree[rootKey]);
            Object.keys(deepObject).forEach((deepKey) => {
              if (Object.prototype.hasOwnProperty.call(deepObject, deepKey)) {
                flatObject[`${rootKey}.${deepKey}`] = deepObject[deepKey];
              }
            });
          } else {
            flatObject[rootKey] = objectTree[rootKey];
          }
        }
      });
    
      return flatObject;
    }
    
    const person = {
      Name: 'Goku',
      Attack: {
        Special: {
          Name: 'Kame Hame Ha',
          Power: '4000'
        },
        Final: {
          Name: 'Genkidama',
          Power: '> 9000'
        },
      }
    }
    
    /* 
      returns:
      {
        Name: 'Goku',
        'Attacks.Special.Name': 'Kame Hame Ha',
        'Attacks.Special.Power': '4000',
        'Attacks.Final.Name': 'Genkidama',
        'Attacks.Final.Power': '> 9000'
      }
    */
    flattenObject(person)
    Copy

    July 27th, 2020

    # Flatten an object of any depth

    Add to bookmarks

    A function which executes itself (so called recursion) is a good way to flatten an object of any depth.

    This algorithm uses two forEach() loops: One for the root layer of the current object and one for it's properties.

    At first, the outer loop will copy the property and it's values into flatObject. If the value is an object itself, the second loop will start.

    The inner loop copies the nested object into the flatObject. The keys of the nested objects will be merged to a dot-notation key like key1.key2.

  • <!DOCTYPE html>
    <html>
      <body>
        <input id="awesomeInput" value="2" />
        
        <script>
          window.$ = document.querySelector.bind(document);
          window.$$ = document.querySelectorAll.bind(document);
          
          setTimeout(() => {
            let awesomeInput = $('#awesomeInput');
            awesomeInput.value = 10;
          }, 5000);
        </script>
      </body>
    </html>
    Copy

    July 26th, 2020

    # Select elements the jQuery-way without jQuery

    Add to bookmarks

    We created a new $and $$ function on the window object via bind(). This way our newly created functions will be the shortcuts for the querySelector and querySelectorAll method.

    The example updates the value of the input from 2 to 10 after 5000 ms by using our jQuery-like selector.

  • let sayan = {
      name: 'Son Goku',
      power: 9001
    }
    
    let character = Object.freeze(sayan);
    character.name = 'Vegeta';
    
    // output: { name: 'Son Goku', power: 9001 }
    console.log(character)
    Copy

    April 12th, 2020

    # Object.freeze() - How to prevent changes to an object?

    Add to bookmarks

    Object.freeze() can prevent changes to an object. If you're in strict mode (use strict; in the first line of your code), your browser will throw an error.

HomeBookmarks