M.js

From ProgZoo
Revision as of 14:37, 19 November 2023 by Andr3w (talk | contribs) (Created page with " let $i = id => document.getElementById(id); let $q = (p,context) => Array.from((context||document).querySelectorAll(p)); function sort(ls,f){ let ret = [...ls]; if (f==...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
let $i = id => document.getElementById(id);
let $q = (p,context) => Array.from((context||document).querySelectorAll(p));
function sort(ls,f){
 let ret = [...ls];
 if (f===undefined){
   ret.sort();
 }else{
   ret.sort((a,b)=>f(a)>=f(b));
 }
 return ret;
}
let range = n => [...new Array(n)].map((_,i)=>i);
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;
}