Skip to content

Instantly share code, notes, and snippets.

@leo60228
Last active June 18, 2018 20:31
Show Gist options
  • Save leo60228/a49b32d03741dc5fa17f8375c7633b75 to your computer and use it in GitHub Desktop.
Save leo60228/a49b32d03741dc5fa17f8375c7633b75 to your computer and use it in GitHub Desktop.
<0.3KB EventEmitter
"use strict";function EventEmitter(){var c=[];return{on:function(d,f){c.push({a:d,b:f})},emit:function(d){c.filter(function(f){return f.a==d}).forEach(function(f){return f.b()})},off:function(d){c.splice(c.indexOf(d),1)}}}
@cookiengineer
Copy link

cookiengineer commented Feb 18, 2017

You can save a lot of bytes when using arrow functions. As the cache (c=[]) is inside a block scope, you should use let and arrow functions for all public methods.

I created a fork to show it: https://gist.github.com/cookiengineer/2c922967803e016c36b373d7fc0be634

"use strict";function EventEmitter() {let c=[];return {on:(a,b)=>c.push({a,b}),emit:d=>c.filter(f=>f.a==d).forEach(f=>f.b()),off:d=>c.splice(c.indexOf(d),1)}};

The final result is 165 Bytes :)

@MRokas
Copy link

MRokas commented Feb 18, 2017

@cookiengineer - arrow functions are ES6.

@cookiengineer
Copy link

Oh, so it's supposed to be ES5 only?

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