Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Dominoes
Sep 20, 2007

Hey dudes, another Q. Can you confirm that there's no way to overload operators in JS? this post seems pretty clean cut, but I'm wondering if there are any tricks. Ie, for the datetime library I'm working on, I'd like to define behaviour to add or subtract timedeltas. I could do it with syntax like this:

JavaScript code:
dateTypes.add(DateOnly(2016, 2, 3), TimeDelta(minutes=3))
but would prefer

JavaScript code:
DateOnly(2016, 2, 3) + TimeDelta(minutes=3)
I think I can't do the kwarg style either, so the delta would have to be TimeDelta(0, 3). Is that right?

Adbot
ADBOT LOVES YOU

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Dominoes posted:

Hey dudes, another Q. Can you confirm that there's no way to overload operators in JS? this post seems pretty clean cut, but I'm wondering if there are any tricks. Ie, for the datetime library I'm working on, I'd like to define behaviour to add or subtract timedeltas. I could do it with syntax like this:

JavaScript code:
dateTypes.add(DateOnly(2016, 2, 3), TimeDelta(minutes=3))
but would prefer

JavaScript code:
DateOnly(2016, 2, 3) + TimeDelta(minutes=3)
I think I can't do the kwarg style either, so the delta would have to be TimeDelta(0, 3). Is that right?

Operator overloading is bad. Use a function.

Roadie
Jun 30, 2013

Dominoes posted:

Hey dudes, another Q. Can you confirm that there's no way to overload operators in JS? this post seems pretty clean cut, but I'm wondering if there are any tricks. Ie, for the datetime library I'm working on, I'd like to define behaviour to add or subtract timedeltas. I could do it with syntax like this:

JavaScript code:
dateTypes.add(DateOnly(2016, 2, 3), TimeDelta(minutes=3))
but would prefer

JavaScript code:
DateOnly(2016, 2, 3) + TimeDelta(minutes=3)

Do it like this:

JavaScript code:
DateOnly(2016, 2, 3).add(TimeDelta({minutes: 3}))
Where DateOnly#add returns another DateOnly (or whatever), so then you can chain more methods onto it.

Dominoes posted:

I think I can't do the kwarg style either, so the delta would have to be TimeDelta(0, 3). Is that right?

See above. You can use an object for parameters, and if you're using ES6 or Typescript, automatically destructure it in the function definition:

JavaScript code:
class TimeDelta {
  constructor ({minutes = 0}) {
    console.log('minutes:', minutes)
  }
}

// or in Typescript
class TimeDelta {
  constructor ({minutes = 0}: {minutes: number}) {
    console.log('minutes:', minutes)
  }
}
If you really want to be fancy, you can support both:

code:
class TimeDelta {
  constructor (...args) {
    let hours = 0
    let minutes = 0

    if (typeof args[0] === 'number') {
      hours = args[0] || 0
      minutes = args[1] || 0
    } else {
      hours = args.hours || 0
      minutes = args.minutes || 0
    }

    console.log('hours:', minutes)
    console.log('minutes:', minutes)
  }
}

// or in Typescript
class TimeDelta {
  constructor (hours?: number, minutes?: number)
  constructor ({hours, minutes}: {hours: number, minutes: number})
  constructor (paramsOrHours?: number | {hours: number, minutes: number}, maybeMinutes?: number) {
    let hours = 0
    let minutes = 0

    if (typeof paramsOrHours === 'number') {
      hours = paramsOrHours || 0
      minutes = maybeMinutes || 0
    } else {
      hours = paramsOrHours.hours || 0
      minutes = paramsOrHours.minutes || 0
    }

    console.log('hours:', minutes)
    console.log('minutes:', minutes)
  }
}

Dominoes
Sep 20, 2007

Thanks dude! I'm going for funcs over methods when able for style reasons. That destructuring syntax in place of kwargs looks perfect. Didn't know about multiple constructors either.

Roadie
Jun 30, 2013

Dominoes posted:

Thanks dude! I'm going for funcs over methods when able for style reasons.

Don't. Everyone will hate you for doing it (and won't use the library), because chained methods is the style that literally everyone else uses.

Edit: When it doubt, use the general style of Immutable.js as a pattern to follow for data-manipulation libraries.

Dominoes posted:

Didn't know about multiple constructors either.

In Typescript, multiple method definitions is basically just sugar over whatever the last method definition is, in that it'll map your typings to whichever is appropriate for documentation/display purposes, but the last one needs to accommodate all of them at once.

Roadie fucked around with this message at 01:17 on May 30, 2017

Honest Thief
Jan 11, 2009
Random question, on these two case statements:

code:
switch(whatever) {
        case 'a':
                return 0; break;
        case 'b': {
                return 1; break;
        } 
}
is a unique closure only created on case b?

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Honest Thief posted:

Random question, on these two case statements:

code:
switch(whatever) {
        case 'a':
                return 0; break;
        case 'b': {
                return 1; break;
        } 
}
is a unique closure only created on case b?

I don't think a closure is created for either. Closures do not map to { }, a closure is not created for if (true) { }. Closures are created around functions.

zombienietzsche
Dec 9, 2003

Honest Thief posted:

Random question, on these two case statements:

code:
switch(whatever) {
        case 'a':
                return 0; break;
        case 'b': {
                return 1; break;
        } 
}
is a unique closure only created on case b?

In a confusingly related concept, case b will create a new scope for ES6 block-scoped variables (const and let) while a won't, since the {} will create a new block.


code:
switch(whatever) {
        case 'a':
		let someVar;
                return 0; break;
        case 'b': {
		// this is OK, since it is a new scope.
		// will hide the someVar defined in case 'a'
		let someVar; 
                return 1; break;
        } 
	case 'c':
		// this will give you a syntax error
		// because someVar has already been declared.
		let someVar;
		return 2; break;

}
Edit: I was unclear with this as other posters have pointed out. There's no closure created in either case. { } does create a new block, though, which effects block-scoped variables. Block-scoped variables are defined with 'const' and 'let' and exist in ES6 only. Just an aside that I mentioned because scoping and closures are related concepts, and it might have been what the OP was thinking of when he asked the original question.

zombienietzsche fucked around with this message at 17:51 on Jun 1, 2017

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

meinstein posted:

In a confusingly related concept, case b will create a new scope for ES6 block-scoped variables (const and let) while a won't, since the {} will create a new block.

This is true, but that is not the same thing as a closure. Upon closer reading your comment, you do mention that.

necrotic
Aug 2, 2005
I owe my brother big time for this!
There are no closures in either case. The brackets for case b only affect scope for variables defined with let.

edit: shoulda reloaded.

Honest Thief
Jan 11, 2009
Ah right, I keep conflating closure with scope a lot. I should keep a reminder close so as to not confuse the two.

Love Stole the Day
Nov 4, 2012
Please give me free quality professional advice so I can be a baby about it and insult you
Stupid class question: this highlighted variable is undefined for some reason?





To quote a similar usage example from the MDN's classes documentation:

php:
<?
class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
    
  ...

  calcArea() {
    return this.height * this.width;
  }
}?>
Clearly I'm forgetting to do one simple dumb thing, right?

5TonsOfFlax
Aug 31, 2001

Love Stole the Day posted:


Clearly I'm forgetting to do one simple dumb thing, right?

Yes, remove const.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Yup, properties cannot be constant. If you need something that is only readable you need to define a property with a getter and no setter.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I'm finally getting around to making a serious effort at using and learning TypeScript on a project...

Am I doing this right?

JavaScript code:
function objValues<T>(obj: { [key: string]: T }): T[] {
    return Object.keys(obj).map(key => obj[key]);
}
The type of the items of the returned array should match the type of the values of the passed in object...right?

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Thermopyle posted:

I'm finally getting around to making a serious effort at using and learning TypeScript on a project...

Am I doing this right?

JavaScript code:
function objValues<T>(obj: { [key: string]: T }): T[] {
    return Object.keys(obj).map(key => obj[key]);
}
The type of the items of the returned array should match the type of the values of the passed in object...right?

That is an appropriate way to use Generics in TypeScript. Now, you may have trouble calling it if the objects you pass in do not explicitly match the { [key: string] : T } type, but you can also simply not fill in the <T> part when calling it and will set T to any.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Skandranon posted:

That is an appropriate way to use Generics in TypeScript. Now, you may have trouble calling it if the objects you pass in do not explicitly match the { [key: string] : T } type, but you can also simply not fill in the <T> part when calling it and will set T to any.

Thanks. I think that objects can only have strings as keys, no? (Well also Symbols, but I don't care about them.)

Dominoes
Sep 20, 2007

Thermopyle posted:

Thanks. I think that objects can only have strings as keys, no? (Well also Symbols, but I don't care about them.)
Correct. Maps are more flexible.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

Correct. Maps are more flexible.

With worse syntax! :(

Dominoes
Sep 20, 2007

Agree; I avoid them for that reason.

huhu
Feb 24, 2006
I have two check boxes that toggle the hidden class for a cell's row in a table based on whether the cell's value is "Incomplete" or "Complete. Is there an easy way to combine the following code because almost all of it is repetitive?

code:
// Toggle Complete Targets
$("#toggleOverallStatusComplete").click(function(){
    $('.col-overallStatus').each(function(){
        var overallStatus = $(this).text();
        if(overallStatus == "Complete"){
            $(this).parent().toggleClass("hidden");
        }
    })
});

// Toggle Incomplete Targets
$("#toggleOverallStatusIncomplete").click(function(){
    $('.col-overallStatus').each(function(){
        var overallStatus = $(this).text();
        if(overallStatus == "Incomplete"){
            $(this).parent().toggleClass("hidden");
        }
    })
});

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Honest Thief posted:

Ah right, I keep conflating closure with scope a lot. I should keep a reminder close so as to not confuse the two.

(AFAIK, getting really picky about what a closure *is*,) A local scope is a closure that you can't pass on to any other code as you could a function, so you're not as wrong as you seem to think.

Just forget let exists and you're good to go :v:

zombienietzsche
Dec 9, 2003
You can refactor the common code out into a separate function. Also, while it shouldn't make a difference in this case, I'd recommend forming a habit to use === instead of == for equality checks.

code:

function toggleHidden(targetClass) {
    $('.col-overallStatus').each(function(){
        var overallStatus = $(this).text();
        if(overallStatus === targetClass){
            $(this).parent().toggleClass("hidden");
        }
    })
}

// Toggle Complete Targets
$("#toggleOverallStatusComplete").click(function(){
    toggleHidden("Complete");
});

// Toggle Incomplete Targets
$("#toggleOverallStatusIncomplete").click(function(){
    toggleHidden("Incomplete");
});

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I
Does anyone have any recommendations for books/online courses/etc for more advanced JavaScript concepts?

I'm pretty confident with most of the syntax, and can accomplish most things with it, but I'm not really sure how "professional" JavaScript is written.

I feel like all the code I write no matter what would make anyone who knows what they are doing slap me in the face.

zombienietzsche
Dec 9, 2003

Edit: A large amount of "professional" JavaScript is written by people that don't know what they're doing, and are flying by the seat of their pants cobbling together half-understood examples from Stack Overflow. If you read those two you'll be streets ahead.

zombienietzsche fucked around with this message at 20:26 on Jun 7, 2017

fantastic in plastic
Jun 15, 2007

The Socialist Workers Party's newspaper proved to be a tough sell to downtown businessmen.

ddiddles posted:

Does anyone have any recommendations for books/online courses/etc for more advanced JavaScript concepts?

I'm pretty confident with most of the syntax, and can accomplish most things with it, but I'm not really sure how "professional" JavaScript is written.

I feel like all the code I write no matter what would make anyone who knows what they are doing slap me in the face.

http://wesbos.com/courses/ has some modern JS courses. His presentation style is a little hit-or-miss for me, but the content's good for the price.

geeves
Sep 16, 2004

ddiddles posted:

Does anyone have any recommendations for books/online courses/etc for more advanced JavaScript concepts?

I'm pretty confident with most of the syntax, and can accomplish most things with it, but I'm not really sure how "professional" JavaScript is written.

I feel like all the code I write no matter what would make anyone who knows what they are doing slap me in the face.

"You Don't Know Java script" is a free book on github.com that's really good and free.

If you want to know how your professional java script should look, look at the airbnb and Google style guides.

MrMoo
Sep 14, 2000

meinstein posted:

Edit: A large amount of "professional" JavaScript is written by people that don't know what they're doing, and are flying by the seat of their pants cobbling together half-understood examples from Stack Overflow. If you read those two you'll be streets ahead.

I've been skimming around on debounce and throttle functions and there are many articles on the topic. Common theme was not to implement your own because libraries are awesome and peer reviewed by Trump himself and so they must be great. So I picked up Lodash and tried their throttle() API and guess what, it is fundamentally flawed and broken, spent this morning rewriting it to be less brain dead but still shines of authors trying too hard for a relatively simple requirement.

quote:

Creates a throttled function that only invokes func at most once per every wait milliseconds.

So the authors decide to implement the rate limit tracking on the incoming calls to the throttle rather than the actual function that is supposed to be throttled. It is just so weird when you attach it to something graphical.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
I'm not sure I understand the objection. How are you using it? What are you expecting to happen, and how is this different from what it actually does?

ROFLburger
Jan 12, 2006

MrMoo posted:

So I picked up Lodash and tried their throttle() API and guess what, it is fundamentally flawed and broken, spent this morning rewriting it to be less brain dead but still shines of authors trying too hard for a relatively simple requirement.

lol?

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Jabor posted:

I'm not sure I understand the objection. How are you using it? What are you expecting to happen, and how is this different from what it actually does?

https://github.com/lodash/lodash/blob/4.17.4/lodash.js#L10911 they just call debounce, which is... sure an interesting implementation decision because I'd expect them to do very different things. I'd expect throttle to queue up calls for later and debounce to throw away calls from before the timeout expired. Sure, you could handle both of those things with one implementation and some options, but I wouldn't expect throttle to be a special case of debounce.

Dominoes
Sep 20, 2007

MrMoo posted:

So I picked up Lodash and tried their throttle() API and guess what, it is fundamentally flawed and broken, spent this morning rewriting it to be less brain dead but still shines of authors trying too hard for a relatively simple requirement.


So the authors decide to implement the rate limit tracking on the incoming calls to the throttle rather than the actual function that is supposed to be throttled. It is just so weird when you attach it to something graphical.
Welcome to Javascript.

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

meinstein posted:


Edit: A large amount of "professional" JavaScript is written by people that don't know what they're doing, and are flying by the seat of their pants cobbling together half-understood examples from Stack Overflow. If you read those two you'll be streets ahead.
These are good, and I'll also throw in Reg Braithwaite's JavaScript Allongé, which is phenomenal at presenting some lighter-weight, FP-oriented ways of approaching JavaScript.

MrMoo
Sep 14, 2000

Jabor posted:

I'm not sure I understand the objection. How are you using it? What are you expecting to happen, and how is this different from what it actually does?

Looks like it has been logged before, they are impressively zealous on closing issues in their tracker:

https://github.com/lodash/lodash/issues/3051

I used it to throttle updates to a Polymer field which is tied to a display item on the page. The Lodash implementation causes the item to randomly double update.



This is my version:

MrMoo fucked around with this message at 18:01 on Jun 8, 2017

necrotic
Aug 2, 2005
I owe my brother big time for this!

MrMoo posted:

Looks like it has been logged before, they are impressively zealous on closing issues in their tracker:

https://github.com/lodash/lodash/issues/3051

They closed it and linked the PR, which then got closed after a week of no response from the PR author.

https://github.com/lodash/lodash/pull/3053

With a project as popular as lodash you need to be pretty aggressive with issues/PRs or you end up with hundreds or thousands that sit forever.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

necrotic posted:

They closed it and linked the PR, which then got closed after a week of no response from the PR author.

https://github.com/lodash/lodash/pull/3053

With a project as popular as lodash you need to be pretty aggressive with issues/PRs or you end up with hundreds or thousands that sit forever.

This is exactly right, and I nominate MrMoo to submit his fixed version.

MrMoo
Sep 14, 2000

"Professional integrator" version, i.e. I copied the debounce() implementation and replaced all Lodash functions with standard ECMA functions where I could be bothered (no exception on function parameter not being a function) and fixed it by using lastInvokeTime instead of lastCallTime for rate checks, everything else as ugly as it was.

http://ahyoomee.miru.hk/donald/throttle/throttle.js

necrotic
Aug 2, 2005
I owe my brother big time for this!
lodash would take a fix (as indicated by the issue/PR threads) so why not fix it there? We don't need a trillionth throttle package.

Also since you copied from lodash maybe give them credit. Or just steal code, that's cool too.

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

necrotic posted:

Or just steal code, that's cool too.
The project license is CC0, public domain, so yeah its pretty cool.

Adbot
ADBOT LOVES YOU

MrMoo
Sep 14, 2000

I think they want a PR and a contributor agreement, :effort:

I haven't decided what to do with it yet, it's just in a branch for testing a specific data flag. It's F/OSS so good luck stealing it.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply