Skip to content

Instantly share code, notes, and snippets.

@SiddharthShyniben
Last active August 6, 2022 04:21
Embed
What would you like to do?
Golfing

A router in 108 89 83 bytes

(a,b,c=_=>(a.find(p=>b=p.path.exec(location.hash))?.render(b),c))=>onhashchange=c()

Shortened with inspiration from @Posandu

const route = (a,b,c=_=>(a.find(p=>b=p.path.exec(location.hash))?.render(b),c))=>onhashchange=c();

const app = document.querySelector('#app');
route([
	{path: /^(#|)$/g, render: () => location.hash = 'home'},
	{path: /^#home$/, render: () => app.innerHTML = 'home'},
	{path: /^#about$/, render: () => app.innerHTML = 'some about stuff'},
	{path: /.*/g, render: () => app.innerHTML = '404'}
])

Minimal templates in 45 bytes

a=>($={})=>a.replace(/#{([\s\S]+?)}/,(_,c)=>eval(c))
const template = a=>$=>a.replace(/#{([\s\S]+?)}/,(_,c)=>eval(c));

document.body.innerHTML = template(`<h1>Hello, #{($ || 'world').toUpperCase()}!`)('Fred');

Bonus: escaping in 144 110 (+99 +65) bytes

a=>$=>a.replace(/#{([\s\S]+?)}/g,(_,c)=>new Option(eval(c)).innerHTML).replace(/#html{([\s\S]+?)}/,(_,c)=>eval(c))
const template = a=>$=>a.replace(/#{([\s\S]+?)}/g,(_,c)=>new Option(eval(c)).innerHTML).replace(/#html{([\s\S]+?)}/,(_,c)=>eval(c));

document.body.innerHTML = template(`Hello, #{$.xss}! #html{$.html}`)({
	xss: `<script>alert(1)</script>`,
	html: `<b>bold</b>`
});

pub-sub in 176 bytes

((a={},b=0)=>({pub:(c,...d)=>Object.entries(a).map(([k,v])=>k.split`-`[0]==c?(v(...d)==!1&&delete a[k],k):0).filter(a=>a),sub:(d,e)=>(a[k=d+--b]=e,k),unsub:k=>delete a[k]}))();
const pubsub = ((a={},b=0)=>({pub:(c,...d)=>Object.entries(a).map(([k,v])=>k.split`-`[0]==c?(v(...d)==!1&&delete a[k],k):0).filter(a=>a),sub:(d,e)=>(a[k=d+--b]=e,k),unsub:k=>delete a[k]}))();

pubsub.sub('event', () => {
	console.log('event fired!');
})

pubsub.sub('event', () => {
	console.log('event fired! this runs only once');
	return false; // stop listening
})

pubsub.pub('event'); // logs twice
pubsub.pub('event'); // logs once (second listener doesnt fire)

const eventID = pubsub.sub('otherthing', () => console.log('other thing'))
pubsub.pub('otherthing'); // logs
pubsub.unsub(eventID)
pubsub.pub('otherthing'); // nothing

pubsub.sub('data', (...data) => console.log(data));
pubsub.pub('data', 1, 'more', ['stuff']) // pass as much as you like
                                         // logs [1, 'more', ['stuff']]

pubsub.sub('test', console.log);
pubsub.sub('test', console.log);
pubsub.sub('test', console.log);
const read = pubsub.pub('test', 'hi')
read //=> ['test-5', 'test-6', 'test-7'] the ids of the listeners that were fired
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment