M.js

From ProgZoo
Revision as of 14:53, 19 November 2023 by Andr3w (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Some handy functions for every day JavaScript

/* returns a new element for a given tag with properties and children */
function $m(tag,props,children){
 let args = [...arguments];
 let ret = document.createElement(args.shift());
 for(let a of args){
   if (typeof a === "string")
     ret.innerHTML = a;
   else if (Array.isArray(a)){
     for(let c of a){
       if (typeof c === 'string'){
           ret.appendChild(document.createTextNode(c))
       }else{
           ret.appendChild(c);
       }
     }
   }else{
     for(let k in a){
       if (k === 'text'){
         ret.innerText = a[k];
       }else if (k.startsWith('on'))
         ret.addEventListener(k.substring(2),a[k]);
       else
         ret.setAttribute(k,props[k]);
     }
   }
 }
 return ret;
}
/* renaming */
let $i = id => document.getElementById(id);
/* querySelectorAll as a list */
let $q = (p,context) => Array.from((context||document).querySelectorAll(p));
/* returns a copy sorted by key function f */
function sort(ls,f){
 let ret = [...ls];
 if (f===undefined){
   ret.sort();
 }else{
   ret.sort((a,b)=>f(a)>=f(b));
 }
 return ret;
}
/* like python... returns a list of integers */
let range = n => [...new Array(n)].map((_,i)=>i);