« first day (2471 days earlier)      last day (2702 days later) » 

21:14
Guys: A question
I have a reference to a function
That's a claim.
I want to create a new function (so that I have a new reference, the callers don't have), that would be exactly equivalent to the reference I have
what would you be using the new reference for?
.bind(null)? or does that return the original reference?
@Luggage That will not work, you changed my this
21:16
null doesn't.
!!> (function(){}).call.call.call.call.call
@towc "function call() {\n [native code]\n}"
@Luggage Sure does.
you just want something that the other things can't change, right?
@towc I want a reference that I can put in a Set, and remove later
But that only I can remove.
I can obviously do something like add [myRef] to the set
And create a new array or object for each
But I was curious to see if that could be avoided.
21:18
!!> let a = () => console.log(1), b = a; b.uniqueId = Math.random(); new Set([ a, b ])
@towc "TypeError: a is not iterable"
@towc {}
Why would that work? b = a same reference
@MadaraUchiha it's actually not
!!> let a = () => console.log(1), b = a; b.uniqueId = Math.random(); [a.uniqueId, b.uniqueId]
@MadaraUchiha 0.39530821508492686
21:20
!!> let a = () => console.log(1), b = a; a.x = 1; [ a.x, b.x ]
Of course it is...
@towc [1,1]
wait wut. I went over this exact process a couple of days ago
@MadaraUchiha [0.9904463327277652,0.9904463327277652]
Why wouldn't it be the same reference?
21:20
function wrap(fn) { return function() { return fn.apply(this, arguments); }; }
All objects behave like this
@Luggage Yes, though I should have mentioned I want to try to avoid the closure
My bad
it can be done without a closure
A closure is less performant than [myFn]
i think.
You could do this
function wrap(fn) { return fn.bind(this); }
But now you've also changed the this from what it originally was
21:23
that binds it right away when you wrap it
(Which is to say: dynamically determined on call)
mine lets it be supplied when called
@Luggage No it doesn't
Yours will set it to window or undefined
interesting behaviour:
What's this inside of your inner function?
21:24
!!> c = () => {console.log(2)}; d = new Function('return ' + c)(); new Set([ c, d ])
@towc {}
No, my bad, you're right
well, more like "hacky" solution
whatever it is when called.
ok now wtf
21:24
Whatever it's called with
I'm getting a set with 2 functions
in the console
@towc Yes, and now call JSON.stringify() on it
this is worse than binding anyway
you could bind the original function to that inner function to avoid the closure.
er.. then you need to screw with arguments.
Here's my usecase btw
21:25
!!> JSON.stringify( new Set([ 1, 2 ]) )
I'm making an event emitter
@towc "{}"
And I want the .on() function (to listen for an event) to return an off() function to remove it
.on can be called several times with the same function reference
So I can't add it to a Set or remove it with .indexOf() from an array
I can store the handlers in tuples of eventName, handlerFn
wait, why would you want a set anyway?
But I wanted to see if I can avoid the O(n) access
21:27
maybe you actually want a function to be called twice on an event
@towc I do, but the removal and addition from/to a Set is O(1)
@MadaraUchiha explain what you're trying to do again
oh, that's what you mean
An event emitter is a low level concept, like a Promise, it needs to be fast.
const em = new EventEmitter();

const off1 = em.on('Hello', () => console.log('world'));

em.trigger('Hello'); // logs 'world'

off1(); // event removed

em.trigger('Hello'); // nothing
@Mosho ^
and the problem
21:30
I want to create a new reference to the function, so that only I have a reference to the actual function I'm calling internally
if .on() is called multiple times with the same reference, you want to allow it to be called multiple times and to individually unregister each?
But this, arguments, closure etc. need to be maintained.
@Luggage Yes, exactly.
how do you feel about attaching a non-enumerable Symbol to functions?
you can just have a counter, you don't need an internal reference, do you?
const em = new MyEventEmitter();
const fn = () => console.log('world');

const off1 = em.on('Hello', fn);
const off2 = em.on('Hello', fn);

em.trigger('Hello'); // logs 'world' twice

off1(); // event removed

em.trigger('Hello'); // logs 'world' once

off2();

em.trigger('Hello'); // nothing
21:31
you can keep track of stuff
yourself
@Mosho With what, indices?
@towc Explain?
@Luggage How does that help me?
I don't know.
@MadaraUchiha for example
I thought it did, then I realized no.
wait, you're implementing a custom event emitter logic, right? That's not your normal event emitter?
21:33
assign an id to each function
@towc Correct
@Mosho And then what?
and return a function that unregisters the function corresponding with the id
is there an em.off() or just the offFunction returned from on()?
@Luggage If it helps, you can implement both
@Mosho Well, the function already has a unique ID, its object entity
how would em.off(ref) work, then?
21:37
I know how to implement this in 10 different ways
I'm wondering if that specific way is possible
To copy a function over to a new reference
@MadaraUchiha but you are differentiating between different calls with the same reference
@Mosho Well, if I can get the copying to work, I'm guaranteed to have only one of any reference in my internal structure
what does wrapping it not give you?
then em.off(ref) wouldn't really be possible. They don't have the internal references
@Mosho It creates a closure
21:39
who cares?
@Luggage Right
the closure is just a hit when created, right?
@Mosho EventEmitter is a low level thing, I'd rather it be as fast as possible
ah
then I would use ids
I'd rather use [myFn] or something like that over a closure
@Luggage No
21:40
function EventEmitter() {
  this.counter = {};
}
EventEmitter.prototype.on = function( event, fn ){
  if( !this.counter[ event ] )
    this.counter[ event ] = {};

  if( !this.counter[ event ][ fn ] )
    this.counter[ event ][ fn ] = 0;

  ++this.counter[ event ][ fn ];

  ... other logic

  return () => {
    --this.counter[ event ][ fn ];
    if( this.counter[ event ][ fn ] === 0 )
      removeFromSet( fn );
  }
}
EventEmitter.prototype.trigger = function( event ) {
  ... proper logic

  for( fn in this.counter[ event ] ) {
It's a hit every time it's called too
keep a data set separate
this doesn't preserve order, but does everything else fine (or should. Didn't check if it actually works, but that's the idea)
ofc add the proper counter and stuff
I just so happen to have a handy test suite for that
const assert = require('assert');
const EventEmitter = require('../emitter.js');


describe("Emitter", function () {
  let emitter;
  beforeEach(function () {
    emitter = new EventEmitter();
  });
  it("can trigger an event", function (done) {
    emitter.on("Hello", function () {
      done();
    });
    emitter.trigger("Hello");
  });
  it("can trigger an event with data", function (done) {
    emitter.on("Hello", function (data) {
      assert.equal(data, "World");
      done();
    });
    emitter.trigger("Hello", "World");
21:41
actually, maybe that's all the logic you need, I think
didn't mean to put the "fn" in the lambda params
@Mosho Again, how does that help me?
Imagine I have an event emitter with thousands or millions of handlers and events
I don't want O(n) on new handler or on removal
Can't escape O(n) for triggering an event
How does an ID on the outside help me here? It sounds like you want me to iterate the data structure and find the ID
hashmap
damn, for ... in on an object with functions as keys returns them as strings :/
otherwise looks like it would work correctly
@towc Heh, that's nothing
Object.keys does the same thing
the only way I can think of to get around that is to use an array for index comparison or something
21:46
var o = {};

o[{x: 1}] = 42;
o[{y: 2}] = 43;

console.log(o[{x: 1}]); // what's printed?
@towc ^ no running
nothing, because that's a new object
Wrong, try again
but it would still work in my case, as long as the functions used have the same reference
@MadaraUchiha this is O(1): jsfiddle.net/ax3v678v
well, undefined?
21:47
Wrong :)
the only other thing I can think of is that keys are actually stored as strings :/
which is awful
welp, returns 43 apparently
oh, yup, stores as string, and those to string are [object Object]...
@Mosho 👍 indeed it is
urgh. This would also mean that two different functions with the same content but different references or "this/arguments" are going to be screwed
just hash it
21:49
or stringify
was muchihas comment a challenge?
obvi that wont work...
guys i need help
@NicholasHendricks Welcome to the JavaScript chat! Please review the room rules. Pleasedon't ask if you can ask or if anyone's around; just ask your question, and if anyone's free and interested they'll help.
It boils down to this: I know how to do it with a map/dictionary
And I also know I can do a bunch of other things
It's not something I need help with, I've done implementations like this before :P
I was curious to know whether a way existed to copy a function to a new reference
Because I couldn't think of one
madara what r u trying to do
copy a function reference. scroll up if you want to know more
21:54
elaborate
function x(){}

copy = x
@Tobiq We just had a 15 minute discussion on the subject
just done it in 2 seconds
21:54
@Tobiq That is the same reference
U want a complete copy of the function?
that is technically copying the reference :)
A "deep copy" if you will
clone function, new reference
21:55
thats not a reference.
thats a copy
I have this chatroom i built using socket.io express and passport and i just added a popup system but everytime a popup shows and you click the ok button the whole page refreshes why would it do that there is nothing that tells it to chat.billischill.ga:8080 just do a random login if you would like to see
which is why u needed to elaborate
scroll up.
@NicholasHendricks Is it a button inside of a form?
why would one need to clone a function?
21:56
Because if it is, that's the default behavior (to submit the form, which by default submits to the same page)
yes
ill show you the snippet
@Tobiq No one here is going to repeat the entire discussion
All of this was already asked and answered
document.body.innerHTML += '<div id="darken-filter" class="darken-filter"></div><div id="popup" class="popup"><div id="popup-title" class="popup-title">' + title + '</div><div id="popup-content" class="popup-content">' + content + '</div><input type="button" value="' + btnValue + '" id="exit-popup" onclick="exitPopup()" class="exit-popup"</input></div>'
oh dear
clone(variable, function) {
variable = eval(function.toString());
}
it looked better in 1 line
21:57
there u go buddy
what ever ur doing is dumb af
Hello all, my brain failed me hence I came asking for assistance. I want to know how would you, easily, create a function like this: I want to create a function that returns n centered elements in a set. E.g.: func(listSize, elmtIndexToReturn) = func(30, 2) => this should return indexes 15, 16 or 15, 14. func(30, 3) => Should return 14,15,16
@Tobiq You destroyed the closure that the original function may have had.
Not equivalent.
is .bind() as bad?
21:58
bind sucks and you change context
what ever ur doing is dumb af, i just cloned the function
@Luggage I was thinking of .bind(), but .bind() necessarily destroys this, even when called with nothing
right
I thought .bind was depreciated
@Tobiq Be nice, no need to be rude
21:59
I don't know why
Also, you did not clone the function
let counter = 0;
const myFn = () => counter++;
Your method fails for this example ^
what u want is to clone the closure too?
@MadaraUchiha technically doesn't :P
good luck
ikr..
@Tobiq I want to clone everything
22:00
ur not calling it from same place.
How nice of him to wish you luck.
what do u expect...
lemme actualy test the function one sec
Oh wait you must not be talking about jQuery
22:01
@Alesana We aren't.
or php
@MadaraUchiha anyway, even if you had a way, it would be as expensive as using a map
what the heck my popup wont refresh the page but when you goto type in a new message and then press enter the page then refreshes
@Mosho Probably
you say you "already have a reference" but you don't
you have 1 reference and you want several
22:02
@MadaraUchiha Hahah okay I'll be quiet :P
something has to be added
how doesnt mine clone?
cos no closure?
@Tobiq Correct
I have no control over the functions I'm accepting
I can't just assume they wouldn't have closure.
So what ur really asking is how to clone the closure?
22:06
@Tobiq no, what I'm really asking is how to create a completely equivalent function in every way, just with a different reference
And what would this be useful for?
document.body.innerHTML += '<div id="darken-filter" class="darken-filter"></div><div id="popup" class="popup"><div id="popup-title" class="popup-title">' + title + '</div><div id="popup-content" class="popup-content">' + content + '</div><input type="button" value="' + btnValue + '" id="exit-popup" onclick="exitPopup()" class="exit-popup"</input></div>'
oh sorry
i did not mean to send that
@Tobiq I already told you that this was answered a few minutes ago
how do u do it
bind?
I meant the usefulness part
22:09
what was the answer?
I'm probably going to opt for a different solution altogether, but I was curious to know if it were possible
i didnt infer it was useless
@BenjaminGruenbaum Thanks for the reply. Sorry, I lost internet connection earlier... I have been looking at TypeScript too, been using vue.js lately and want to convert the project to ts. Why did you switch to TypeScript, what made you change your view on types?
clone = func.bind()
useless
I tried it every few months and started liking it when it started working @Schoening
22:11
i append that above code to the body and then when you click the button it removes all of those divs but then when you goto hit the submit button on the chat form it just refreshes the page even though i have this
1 message moved to Trash can
@NicholasHendricks Please don't post unformatted code - hit Ctrl+K before sending, use up-arrow to edit messages, and see the faq. For posting large code blocks, use a paste site like gist.github.com, hastebin.com, pastie.org or a demo site like jsbin.com
    $('form').submit(function(e) {
        e.preventDefault();

        var message = {
            text: $('#message-text-input').val()
        }

        if (message.text.trim().length !== 0) {
            var timestamp = new Date().toLocaleDateString("en-US") + ", " + new Date().toLocaleTimeString("en-US");
            socket.emit('chat', socket.username, message.text);
            $('#message-text-input').focus().val('');
        }
    });
there
@Schoening Types are awesome until they're in the way
TypeScript tries very hard to not get in your way
@Tobiq You destroyed this
Not equivalent.
@BenjaminGruenbaum Are your familiar with a way to clone a function without creating a closure and without destroying the function's context/closure?
oh really??

clone=x.bind(this)
waste of clock cycles
@MadaraUchiha what do you mean by cloning a function?
You just take a reference to it - or create another function which decorates it.
22:14
@Tobiq Still destroyed this, you bound it to the this at this point, but this should be bound when the function is called
The function reference holds the closure.
@Tobiq This is your second warning, be nice
thats what would happen...
warning for what?
Being rude, you've had many already.
var _ref = myObjsct.someFunction;
var copy = function(...args) { return _ref.call(this, ...args); }
myObject.someFunction = copy;
// create more copies as required
22:15
@BenjaminGruenbaum Right, so it's impossible to avoid copy having an additional closure "layer"?
@MadaraUchiha your requirement is that modifying the original should not affect your function reference?
@BenjaminGruenbaum Yes
I'm looking for something like util.promisfy that creates a new function without introducing a closure.
@MadaraUchiha that just introduces an anonymous function - it has no closure
util.promisify creates a new function after all
@BenjaminGruenbaum So it destroys the closure of the original?
copy closes over nothing
22:18
let counter = 0;
function wat(callback) {
  callback(null, counter++);
}

const asyncWat = util.promisify(wat);
What would happen here?
No, why would it "destroy" the closure?
Obviously anything the original function closes over is still closed over.
Then I'm confused.
Closures are lexical, they are about what's in the same scope as the function.
You can't just "access" them or modify them outside the lexical scope - that's the lexical scoping part of JS
(except with, but let's not discuss that)
@BenjaminGruenbaum I'm making a low level something
I want to avoid creating closures every time I need to wrap a function
I essentially want to create a reference only I have, but still be able to call the function
For that matter, I could use let myRef = [myFn] and use myRef later (add things to it, add it to a set, remove it from a set, etc)
or just do let myRef = myFn?
Arguments in JavaScript have reference value semantics (that is, functions gets the reference value and not the reference itself as arguments). If you have a reference to myFn just keep the reference.
Also, what are you making?
(Just keep the reference as in - no one can mutate it)
(of course, if myFn chooses a function based on a closure property then you can't win and making a copy won't help you anyway - because closures provide privacy you can't override)
Which brings me to ask - what's the X of your XY?
22:23
@BenjaminGruenbaum This is a theoretical experiment I'm having with our EventEmitter question
What's the experiment?
@BenjaminGruenbaum I've been thinking of having the bucket of functions in a Set, under the assumption that a set would be faster to add/remove from than an array (now or in the future)
But then, if you do use a Set, then the consumer wouldn't be able to add the same function to the same handler
I need a new reference
Since we don't have hashsets
@MadaraUchiha typically, an EventEmitter has up to 10 listeners tops (after 8 you get a warning from Node) - I don't think data structures would matter here
@BenjaminGruenbaum Of course it doesn't matter, hence why it's a theoretical experiment
You can use a set of functions but then if someone adds the same handler twice you lose.
22:26
@BenjaminGruenbaum Unless I manage to create a new reference for the function that's passed in
For example, by wrapping it in a new array
@MadaraUchiha or just make it a multiset (or for the lack of in JS - a Map of functionRef -> count.
const fn = () => {};

[fn] !== [fn]
Wrapping it in a new array is silly, because then when you need to remove it you can't find a reference to it which misses the point.
A multiset (by a Map) works but meh.
@BenjaminGruenbaum Hmm, yeah
That's also an option
wat
Oh nvm, I should learn to read
22:34
Here
class MultiSet {
  constructor() {
    this.d = new Map();
  }
  add(el) {
    this.d.set(el, (this.d.get(el) || 0) + 1)
    return this;
  }
  has(el) { return this.d.has(el); }
  delete(el) {
    if(!this.d.has(el)) {
      return false;
    }
    let val = this.d.get(val);
    if(val === 1) {
      this.d.delete(el);
    } else {
      this.d.set(el, val - 1);
    }
    return true;
  }
  clear() { this.d.clear(); }
  *entries() {
    for(const [key, count] in this.d.entries()) {
      for(let i = 0; i < count; i++) yield [key, key];
@MadaraUchiha just wrote in console, so wasn't rested
wait, bug
We all know that code needs to be properly rested before use.
class MultiSet {
  constructor() {
    this.d = new Map();
  }
  add(el) {
    this.d.set(el, (this.d.get(el) || 0) + 1)
    return this;
  }
  has(el) { return this.d.has(el); }
  delete(el) {
    if(!this.d.has(el)) {
      return false;
    }
    let val = this.d.get(val);
    if(val === 1) {
      this.d.delete(el);
    } else {
      this.d.set(el, val - 1);
    }
    return true;
  }
  clear() { return this.d.clear(); }
  *entries() {
    for(const [key, count] of this.d.entries()) {
      for(let i = 0; i < count; i++) yield [key, key];
Ok, works now
It's not really a set since sets are iterated in insertion order but who cares @MadaraUchiha :D
23:35
I love everybody
@KamilSolecki ❤️
Ily2 kendall
Square space is stupid
Circular space ftw
ur a stupid
23:45
hey guys i was wondering if there were any new users on that could help me with a problem i made a popup system wich adds this when the function is called

socket.on('popup', function(title, content, btnValue, type) {
document.body.innerHTML += '<div id="darken-filter" class="darken-filter"></div><div id="popup" class="popup"><div id="popup-title" class="popup-title">' + title + '</div><div id="popup-content" class="popup-content">' + content + '</div><input type="button" value="' + btnValue + '" id="exit-popup" onclick="exitPopup()" class="exit-popup"</input></div>'
big message sorry
Wow format plz
i did ctrl k hoping it would tab right it actually looked better at first i am sorry
Don't be sorry, just format.
Wow autocorrect makes me appear not drunk
I wonder if Lil Wayne ever gets called Lil Wang
23:56
or lil brain
Don't get me started on hip hop
Tell me what y'all like, and I WILL provide
@KamilSolecki rock

« first day (2471 days earlier)      last day (2702 days later) »