Skip to content

Instantly share code, notes, and snippets.

@tangentstorm
Last active April 9, 2024 11:05
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tangentstorm/4f271600fc20404150e05c373109551d to your computer and use it in GitHub Desktop.
Save tangentstorm/4f271600fc20404150e05c373109551d to your computer and use it in GitHub Desktop.
shorthand javascript
// sh.mjs: javascript shorthand
// array helpers (apl/j/k)
export const id=x=>x
export const af=(n,x)=>Array(n).fill(x) // TODO: make this 'afl' or 'fil' (aa?)
export const ii=(n,f)=>{for(let i=0;i<n;i++)f(i)}
export const im=(n,f)=>af(n,0).map((_,i)=>f(i))
export const ia=(n,f)=>im(n,id)
export const at=(a,ixs)=>ixs.map(i=>a[i])
export const io=(xs,ys)=>ys.map([].indexOf.bind(xs))
export const a0=a=>a[0]
export const a1=a=>a[1]
export const odom=(x,y)=>{
let r=[];
for(let j=0;j<y;j++) for(let i=0;i<x;i++) r.push([i,j]); return r }
// -- misc js shorthand
export const {min,max,sin,tan,cos}=Math
export const ran=Math.random
export const flo=Math.floor
export const cei=Math.ceil
export const rou=Math.round
export const int=parseInt
export const srt=(a,f)=>a.toSorted(f)
export const len=x=>x.length
export const doc=document
export const und=x=>x===undefined
export const arf=Array.from // TODO: make this 'af'
export const oks=Object.keys
export const oas=Object.assign
export const log=console.log.bind(console)
export const raf=window.requestAnimationFrame
export const chr=String.fromCodePoint
export const ord=s=>s.length==1?s.codePointAt(0):arf(s).map(ord)
export const ftx=(u,cb)=>fetch(u).then(r=>r.text()).then(cb)
export const fjs=(u,m,d)=>{
let f = (und(m)||m==='GET') ? fetch(u)
: fetch(u,{method:m,headers:{'Content-type':'application/json'},
body:jss(d)})
return f.then(r=>r.json())}
export const jsp=JSON.parse
export const jss=JSON.stringify
export const ce=(t,a,es)=>app(ats(doc.createElement(t),a),...es||[])
export const cen=(n,t,a,es)=>app(ats(doc.createElementNS(n,t),a),...es)
export const svg=(t,a,es)=>(es||=[],cen(svg.ns,t,a,es))
svg.ns='http://www.w3.org/2000/svg'
export const ani=(a)=>new Animation(a)
export const kfe=(e,ks,o)=>new KeyframeEffect(e,ks,o)
export const akf=(e,ks,o)=>ani(kfe(e,ks,o))
export const S=(a,es)=> svg('svg',oas({
width:640,height:480,viewBox:'-320 -240 640 480'},a),es)
export const C=(a)=>svg('circle',oas({cx:0,cy:0,r:0},a))
export const R=(a)=>svg('rect',oas({x:-5,y:-5,width:10,height:10},a))
export const G=(a,es)=>svg('g',a,es)
// -- dom shorthand
export const att=(e,a,v)=>und(v)?e.getAttribute(a):(e.setAttribute(a,v),e)
export function ats(e,kv) {
if (kv) for (let k in kv) e.setAttribute(k,kv[k]); return e}
export const sty=(e,a,v)=>und(v) ? e.style[a] : (e.style[a]=v,e)
export const hat=(e,a)=>e.hasAttribute(a)
export const app=(x,...ys)=>((x.append||x.push).bind(x)(...ys),x)
export const iht=(e,h)=>und(h)?e.innerHTML:(e.innerHTML=h,e)
export const itx=(e,t)=>und(t)?e.innerText:(e.innerText=t,e)
export const cla=(c,e)=>(e.classList.add(c),e)
export const clr=(c,e)=>(e.classList.remove(c),e)
export const gbc=(e)=>e.getBoundingClientRect()
function ei0(x,y) {
let [base, id] = (y===undefined) ? [doc,x] : [x,y]
return base.getElementById(id)}
export const ei=new Proxy(ei0, {
get:(ei,v)=>ei(v),
apply:(ei,th,args)=>ei.apply(th,args)})
export function qs(x,y) {
let [base, id] = und(y) ? [doc,x] : [x,y]
return base.querySelector(id)}
export function qsa(x,y) {
let [base, id] = und(y) ? [doc,x] : [x,y]
return arf(base.querySelectorAll(id))}
export function ael(x,y,z) {
let [base, ev, cb] = und(z) ? [doc,x,y] : [x,y,z]
return base.addEventListener(ev, cb)}
export const onl=(f)=>ael('DOMContentLoaded',f) // 'on load'
export const onc=(e,f)=>ael(e,'click',f) // 'on click'
export function mob(cb,e,c){
let res = new MutationObserver(cb)
if (e) res.observe(e,c)
return res}
// -- tool to install everything in a namespace
import * as sh from './sh.mjs'
export function glosh(ctx0,quiet) {
let ctx = ctx0??globalThis
if (!quiet) {
log(`installing sh.* on ${ctx}:`)
log(`[${oks(sh).join(' ')}]`)}
oks(sh).forEach(k=>(ctx[k]=sh[k])) }
globalThis.$sh=glosh // $sh() will make all global
glosh(glosh,1) // register $sh.xxx globally
@tangentstorm
Copy link
Author

example usage

image

// terse animation
app(iht(doc.body,''),
    ce('input',{id:'scrub',type:'range',min:0,max:100,value:0}),
    ce('br'),
    S({style:'background:gold'},[
      R({fill:'red',y:-50}),
      ...im(7,i=>C({cx:50*i-150,cy:0,r:10,id:'c'+i}))]))
a=akf(ei.c1,[0,100,0,-100,0].map(x=>({cy:x})),
      {duration:1000,iterations:2,fill:'forwards'})
ei.scrub.oninput=e=>
  a.currentTime=a.effect.getTiming().duration*ei.scrub.value/100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment