/ Gists / JavaScript

Gists - JavaScript

On gists

Proxy - nested

JavaScript

NestedProxy.js #

const user = {
  a: 'A',
  b: {
    c: "C",
    d: "D"
  },
  x: {
    y: {
      z: {
        first: "first nested",
        second: "second nested"
      }
    }
  }
}


const createNestedProxy = (obj) => {
  return new Proxy(obj, {
    get(target, prop) {
      const props = prop.split('.');
      let value = target;
      for (const p of props) {
        value = value[p];
        if (value === undefined) return undefined;
      }
      return value;
    }
  });
};

const nestedUser = createNestedProxy(user);

console.log(nestedUser["b.c"]); // Vypíše: "C"
console.log(nestedUser["x.y.z.first"]); // Vypíše: "first nested"

On gists

Promise - withResolvers

JavaScript

Promise.js #

// neni nutne vracet new Promise jak je vsude v prikladech

// 1
async function test () {
	let resolve, reject;

const promise = new Promise((res, rej) => {
  resolve = res;
  reject = rej;
});

	setTimeout(() => {
	 Math.random() > 0.5 ? resolve("ok") : reject("not ok");

	}, 1500)

	return promise	
}

test().then(res => console.log(res)).catch(err => console.log(err))


// 2
const { promise, resolve, reject } = Promise.withResolvers();
Math.random() > 0.5 ? resolve("ok") : reject("not ok");

On gists

Async (mark function as async??)

JavaScript

async.js #

// https://stackoverflow.com/questions/44106907/when-to-mark-function-as-async

async function fnUsingAsync() {
    // Synchronously throw half of the time
    if (Math.random() < .5)
        throw new Error('synchronous error')

    // Return fulfilled/rejected promises half of the time
    return Math.random() < .5 ?
        Promise.resolve('success') :
        Promise.reject(new Error('asynchronous error');
}

function fnNotUsingAsync(x) {
    // Use the exact same body here than function above
}



// when using the async keyword, the function always returns a promise
// which can be fulfilled or rejected.
// No need for try-catch!
fnUsingAsync()
    .then(result => /* result === 'success' */)
    .catch(error => /* catch both synchronous and asynchronous error */);

// Otherwise, you will need to use a try-catch statement, because
// the exception won't be converted to a rejected promise.
try {
    fnNotUsingAsync()
      .then(result => /* result === 'success' */)
      .catch(error => /* catch asynchronous error only */)
}
catch (error) {
    /* catch synchronous error only */
}

On gists

JS plugin aka jQuery

JavaScript Plugin patterns Helpers-Filters-Plugins

Test.plugin.js #

class Test {
    constructor(el, options) {
        this.el = el;
        const defaultOptions = {
            onHover: (element, e) => {
                console.log(':)))', element, e);
            },
        };

        this.options = { ...defaultOptions, ...options };
        this.mouseOverHandler = this.handleMouseOver.bind(this); // Vytvoření odkazu na metodu handleMouseOver
    }

    init() {
        this.el.addEventListener('mouseover', this.mouseOverHandler); // Přidání posluchače události
    }

    destroy() {
        this.el.removeEventListener('mouseover', this.mouseOverHandler); // Odstranění posluchače události
    }

    handleMouseOver(e) {
        if (this.options.onHover) {
            this.options.onHover(this.el, e);
        }
    }
}

On gists

jQuery $.data in vanilla js

JavaScript

implementations.js #

/* 1 */
var item = document.getElementById("hi");
console.log(item);

item.data = {getType: function(){return this.TYPE},TYPE:"winner"};

var out = item.data.getType();
console.log("out", out);

var two = document.getElementById("hi")
console.log("should say 'winner': ", two.data.getType());



/* 2 */
window.$ = {
    data: function(obj, key, val) {
        if(!obj) {
            return this._data;
        } else if(!key) {
            if(!(obj in this._data)) {
                return {};
            }
            return this._data[obj];
        } else if(arguments.length < 3) {
            if(!(obj in this._data)) {
                return undefined;
            }
            return this._data[obj][key];
        } else {
            if(!(obj in this._data)) {
                this._data[obj] = {};
            }
            this._data[obj][key] = val;
        }
    },
    _data: {}
};

$.data(document.body); // Returns {} because no data has been set for this object
$.data(document.body, 'lastUpdate', new Date());//Sets 'lastUpdate' of obj to current time
$.data(document.body, 'lastUpdate'); // Gets previously set time
$.data(document.body); // Gets object of all data, including 'lastUpdate' time
$.data(document.body, 'nonexistant'); // Returns undefined because property was never set
$.data(); // Returns all metadata




/* 3*/
/** A storage solution aimed at replacing jQuerys data function.
 * Implementation Note: Elements are stored in a (WeakMap)[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap].
 * This makes sure the data is garbage collected when the node is removed.
 */
window.dataStorage = {
    _storage: new WeakMap(),
    put: function (element, key, obj) {
        if (!this._storage.has(element)) {
            this._storage.set(element, new Map());
        }
        this._storage.get(element).set(key, obj);
    },
    get: function (element, key) {
        return this._storage.get(element).get(key);
    },
    has: function (element, key) {
        return this._storage.has(element) && this._storage.get(element).has(key);
    },
    remove: function (element, key) {
        var ret = this._storage.get(element).delete(key);
        if (!this._storage.get(element).size === 0) {
            this._storage.delete(element);
        }
        return ret;
    }
}

var myElement = document.getElementById("myId");
dataStorage.put(myElement, "myKey", "myValue");

On gists

Configuration options object

Popular ⭐ JavaScript Vue.js

options.js #

// JS
function setPreferences({ theme = 'dark', layout = 'grid' } = {}) {
  console.log(`Preferences set: Theme - ${theme}, Layout - ${layout}`);
}

export function useRefHistory(ref, options) {
  const {
    deep = false,
    capacity = Infinity,
  } = options;

  // ...
};

// https://michaelnthiessen.com/tips/options-object
export function useRefHistory(ref, options) {
  const {
    deep = false,
    capacity = Infinity,
    ...otherOptions,
  } = options;

  // Pass along some options we're not using directly
  useSomeOtherComposable(otherOptions);
};

On gists

Labels for Loops and Block Statements

JavaScript

loop.js #

outerLoop: for (let i = 0; i < 5; i++) {
    innerLoop: for (let j = 0; j < 5; j++) {
        if (i === 2 && j === 2) break outerLoop;
        console.log(`i=${i}, j=${j}`);
    }
}

On gists

Map - new Map ...

JavaScript

map.js #

const data = [
	{
		id: 1,
		user: 'Kcko',
		gender: 'M'
	},
	{
		id: 2,
		user: 'Superman',
		gender: 'M'
	},
	{
		id: 3,
		user: 'WonderWoman',
		gender: 'F'
	}
];



const hashData = new Map(data.map(user => [user.user, user]))

hashData.set('Kunda', {
	id: 100, 
	user: 'pan Kunda',
	gender: 'NB'
})

console.log(hashData)
console.log(hashData.get('Kcko'))

On gists

Catching async/await

JavaScript

how-to-catching.js #

function getUserInfo() {
     return new Promise((resolve, reject) => {
         setTimeout(() => {
             reject('request exception')
         }, 1000)
     })
}


// 1) Try-catch
async function loggedIn() {
     try {
         let userInfo = await getUserInfo()
         // Execution interrupt
         let pageInfo = await getPageInfo(userInfo?.userId)
     } catch(e) {
         console.warn(e)
     }
}


// 2 direct catch
async function loggedIn() {
   let userInfo = await getUserInfo().catch(e => console.warn(e))
   // Execution continues, userInfo might be undefined
   if (!userInfo) return
   let pageInfo = await getPageInfo(userInfo?.userId)
}

// 3 direct catch with handle
async function loggedIn() {
   let userInfo = await getUserInfo().catch(e => {
       console.warn(e)
       return Promise.reject(e)
   })
   // Execution interrupt
   let pageInfo = await getPageInfo(userInfo?.userId)
}

On gists

Importing JSON file

JavaScript Vue.js

foo.js #

// ES 6, JS without bundlers

// 1) fetch('data.json').then().then() ...
// 2) import data from './data.json' assert { type: 'json' };


// Vue
async function fetchData() {
    try {
        const response = await import('@/data.json');
        const data = await response.default; // Získání dat z Promise
        console.log(data);
    } catch (error) {
        console.error('Chyba při načítání dat:', error);
    }
}


// Or
const o = ref([]);
const data = import('@/data.json').then(x => {
    o.value = x.default;
});