M.js

From ProgZoo
Revision as of 14:46, 19 November 2023 by Andr3w (talk | contribs)
Jump to navigation Jump to search
/* returns a new element for a given tag with properties and children */
/* Example use...
document.body.append($m('div',{style:'border:solid;padding:1ex;'},[
  'This is a button ',
  $m('button',{onclick:()=>alert('Hello World')},'Say Hello')
]));
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);