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
Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Thermopyle posted:

lodash has been the better alternative to underscore for years now.

Yes, that's classic JS community for you.

Well, since it has been years, plural, what is the alternative to lodash and then the alternative to that?

Adbot
ADBOT LOVES YOU

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

Wheany posted:

Well, since it has been years, plural, what is the alternative to lodash and then the alternative to that?

I think lodash is still king for now. It's been actively developed, and also allows you to only include the functions you need if you don't want the whole library.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Suspicious Dish posted:

I never really followed underscore / lodash because most of the utility functions seem nearly pointless or so obvious to write to not matter.

For small projects I might still consider lodash if I want to be sure the thing works with like IE8, but I think most frameworks come with their own polyfill for browsers that don't support filter/map/some and similar functions.

darthbob88
Oct 13, 2011

YOSPOS

Suspicious Dish posted:

well, I would first have asked them what happens when I hand them two strings of uneven length, because that seems like an obvious prompt and one they want you to ask.
Or try and put numbers to "all its string arguments", yeah. That wasn't really an option, though, since this was just part of the application process. "Give us your name, email, resume, and a CodePen/JSFiddle with a function that can do this." And apparently this is a pretty good way to do it, apart from not using library functions. So at least I don't have to worry about getting rejected because of that.

Thermopyle
Jul 1, 2003

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

Suspicious Dish posted:

I never really followed underscore / lodash because most of the utility functions seem nearly pointless or so obvious to write to not matter.

Yeah, same. I just kind of, through osmosis I guess, gradually became aware of the fact that people who know about things had a higher opinion of lodash.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





underscore/lodash makes a lot of things for people who don't really care to write functions themselves and are concerned about compatibility. their functions also run faster than the native javascript functional implementations (apparently for-loops are faster, and I'm also guessing this is engine dependent).

The biggest difference between them is lodash:

1. uses semver
2. is faster (all those jsperf tests were done ~2+ years ago, but I doubt there's been work done on it from the underscore side. I may be wrong though)
3. doesn't require you to call _chain() to chain functions.
4. allows custom builds
5. has extra util function

But now they have basically decided to merge them all (underdash) but I guess the two libraries have become so far separated that they're now working to get "core" functions the same first.

Sedro
Dec 31, 2008
They're faster because they don't concern themselves with edge cases like sparse arrays, while the native combinators need to be compliant with the spec

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

They're faster because they don't have to transition in and out of native code, or even thunk to the privileged implementations for self-hosted cases. Handling sparse arrays is very cheap in native implementations.

Sedro
Dec 31, 2008
What's stopping me from using JS implemented builtins if they're faster and fully compliant?

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Nothing? Syntax convenience, possibly. Most of the time the performance of that construct isn't very important, but if it shows up in a profile go nuts.

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

Sedro posted:

What's stopping me from using JS implemented builtins if they're faster and fully compliant?

Nothing? You should use them if they are faster. Things like lodash supply functions that are either not in JS at all, not implemented consistently across browsers, or where the syntax keeps changing and you want a standardized one.

Chenghiz
Feb 14, 2007

WHITE WHALE
HOLY GRAIL
Lodash is nice for stuff like groupBy too. I find it easier to just install lodash than try to maintain my own untested set of helper functions to perform the same things - what's the point? Obviously if you're just using map and filter most of the time, you don't need it though.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

The "array extras" in ES5 were added not for improved performance but so that people wouldn't keep writing their own buggy versions of those functions, which was common in the Firefox codebase alone. The set will keep growing over time.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Does anyone know in TypeScript how to define an interface that has a static method, or a good alternative?

Basically what I'm doing is making a game and I'm working on creating saved games. I want every object in the game to be able to serialize itself out to a JSON object and then deserialize the object in to an instance of itself. I have an interface called Serializable which works for the serializing part, but it doesn't look like interfaces can let you define a static method for deserializing.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Subjunctive posted:

They're faster because they don't have to transition in and out of native code, or even thunk to the privileged implementations for self-hosted cases. Handling sparse arrays is very cheap in native implementations.

Silly question: why don't you write your array methods in JS so that your JIT can inline them or such, and you don't have to go in/out of native code?

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

piratepilates posted:

Does anyone know in TypeScript how to define an interface that has a static method, or a good alternative?

Basically what I'm doing is making a game and I'm working on creating saved games. I want every object in the game to be able to serialize itself out to a JSON object and then deserialize the object in to an instance of itself. I have an interface called Serializable which works for the serializing part, but it doesn't look like interfaces can let you define a static method for deserializing.

I don't think an interface makes much sense here, but have you tried using an abstract class?

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Skandranon posted:

I don't think an interface makes much sense here, but have you tried using an abstract class?

An abstract class makes sense, using an abstract class I've got this:

code:
abstract class Deserializable<DeserializedType, SerializedType> {
    static deserialize<DeserializedType, SerializedType>(data: SerializedType): DeserializedType {
        throw new Error("Must be overriden");
        return null;
    }
}
Which isn't the best since it throws a runtime error if something hasn't overridden it instead of a compilation error, but it seems like it'll work out well enough.

Not sure if I even need to have a common interface for this anyway though, I can probably make do with just having classes have their own deserialize method without a common signature since I won't be using it in a common way (i.e. I'm always calling deserialize when I know the exact type of the thing I'm deserializing).

piratepilates fucked around with this message at 22:06 on Jan 30, 2016

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me
Is it that important for the method to be static? A normal interface with a deserialize method would give you the compile time warning.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Skandranon posted:

Is it that important for the method to be static? A normal interface with a deserialize method would give you the compile time warning.

I think I just liked the idea of having a function that returns a new instance with the properties set right, instead of having to create a new instance and then call a method on it to set up everything. In the end you would have to pass in the same arguments to the static function and the constructor anyway so it's not like it changes much, and all it would save would be one line so I may just go with an instance method on the class instead of a static method.

But I also just realized that I'm using implements with the abstract Deserializable class anyway, so the type information would be realized at compile time since no class in this application would extend Deserializable.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Suspicious Dish posted:

Silly question: why don't you write your array methods in JS so that your JIT can inline them or such, and you don't have to go in/out of native code?

It's been done, and it can be better, but thunking into the privileged library has cost as well. They can be redefined by script code as well, so you need to get the sharing right. Compared to inlining the statements in a loop directly, it's always going to lose at least by a bit. Nobody I know of does inter-procedural LICM or such, though maybe that's changed if things are being inlined aggressively enough. I should check.

Most arrays are small, though, so it really doesn't matter that there's more overhead. If you're walking a 10K buffer, speak with your profiler.

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

piratepilates posted:

I think I just liked the idea of having a function that returns a new instance with the properties set right, instead of having to create a new instance and then call a method on it to set up everything. In the end you would have to pass in the same arguments to the static function and the constructor anyway so it's not like it changes much, and all it would save would be one line so I may just go with an instance method on the class instead of a static method.

But I also just realized that I'm using implements with the abstract Deserializable class anyway, so the type information would be realized at compile time since no class in this application would extend Deserializable.

OO in TypeScript is strange because OO in JavaScript is strange. I'm trying to do some Electron/Angular development, and the node.d.ts from DefinatelyTyped doesn't work well with Internal modules. Angular.d.ts is written in a nice way which lets it be used in both Internal and External modules, but not node. I'm currently going with "make my own fake interface for things I want to use" but I don't see another way other than writing my own node.d.ts.

0zzyRocks
Jul 10, 2001

Lord of the broken bong
Going along with the "OO in JS" discussion, anyone ever use JOII? I'm using it on a project (an older version at least) and I don't dislike it, but I'm not sure the overhead is worth it (in favor of more basic native JS). http://joii.harold.info/ and https://github.com/haroldiedema/joii

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

0zzyRocks posted:

Going along with the "OO in JS" discussion, anyone ever use JOII? I'm using it on a project (an older version at least) and I don't dislike it, but I'm not sure the overhead is worth it (in favor of more basic native JS). http://joii.harold.info/ and https://github.com/haroldiedema/joii

Can't say I've used it, but based on the description, TypeScript seems better in every way (unless you really REALLY hate the transpiling part). It can target ES3 if you want, is a strict superset of JS, and has some phenomenal tooling. Also, having a compile step is pretty much a complete plus to me, as it enables a ton of type checking to be done at compile time, which can catch a ton of dumb mistakes and makes a whole class of previously required unit tests unnecessary. It also allows usage of features in ES6 that are not yet actually implemented, and when later ES6 is fully supported, you don't need to change your TS code at all, simply by changing your compilation target.

tyrelhill
Jul 30, 2006

0zzyRocks posted:

Going along with the "OO in JS" discussion, anyone ever use JOII? I'm using it on a project (an older version at least) and I don't dislike it, but I'm not sure the overhead is worth it (in favor of more basic native JS). http://joii.harold.info/ and https://github.com/haroldiedema/joii

The leaps and bounds people go to shoehorn stuff like this into JavaScript will never cease to amaze me.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

tyrelhill posted:

The leaps and bounds people go to shoehorn stuff like this into JavaScript will never cease to amaze me.

When you are the only language that runs in a browser, people will do unspeakable things to make you like the language they like.

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

Lumpy posted:

When you are the only language that runs in a browser, people will do unspeakable things to make you like the language they like.

"If you can't be with the one you love, love the one you're with".

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



It seems like the appeal of that over anything else (mostly TypeScript, maybe Flow, but really TypeScript) is not needing to use a compiler.

But gently caress that, use a compiler, use webpack and have all your nice little add-ons and improved languages. It is actually very simple to get a small version of Webpack running, and not hard to add more stuff (loaders, chunks) in there when needed. It's like using Dropbox instead of Git because it's easier to just move files somewhere.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
Okay, I'm just getting my feet wet with promises, and I feel like I'm in crazy land.

code:

var Promise = require('bluebird');
var bcrypt = require('bcrypt-nodejs');
Promise.promisify(bcrypt.hash);


Search.hashPassword = function(password){
  bcrypt.hash(password, null, null, function(err,hash){

      if(err){
          console.log('i am an error');
      }else{
          console.log('I am the hash', hash);
          return hash;
      }
  }).then(function(res){
    console.log('did you even make it to the promise stage?', res);
  })
}
No matter how many ways I slice this, I always get some variation of "Cannot read property 'then' of undefined". hash turns up fine in the console.log. I know I'm misunderstanding something fundamentally simple here, but after 6 hours, I just can't see it.

I can just throw a callback into the else statement and pass hash there, but that really feels like cheating.

Help me devs, you're my only hope.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Raskolnikov2089 posted:

Okay, I'm just getting my feet wet with promises, and I feel like I'm in crazy land.

code:

var Promise = require('bluebird');
var bcrypt = require('bcrypt-nodejs');
Promise.promisify(bcrypt.hash);


Search.hashPassword = function(password){
  bcrypt.hash(password, null, null, function(err,hash){

      if(err){
          console.log('i am an error');
      }else{
          console.log('I am the hash', hash);
          return hash;
      }
  }).then(function(res){
    console.log('did you even make it to the promise stage?', res);
  })
}
No matter how many ways I slice this, I always get some variation of "Cannot read property 'then' of undefined". hash turns up fine in the console.log. I know I'm misunderstanding something fundamentally simple here, but after 6 hours, I just can't see it.

I can just throw a callback into the else statement and pass hash there, but that really feels like cheating.

Help me devs, you're my only hope.

You don't seem to actually be creating a promise there, so you're attaching a .then call to what is probably 'void' since bcrypt.hash() probably won't return anything when you're calling it in async mode (which you are since you're passing it a callback with the function(err,hash){}).

If the function doesn't return a promise then you need to get your promise implementation to force a promise out of that. If you're using something like bluebird or Q then there's a function that will automatically convert the async function call to something that returns a promise (I forget the specific of it, it should be on their github page), or by creating the promise yourself like this:

code:
Search.hashPassword = function(password){
  bcrypt.hash(password, null, null, function(err,hash){

      if(err){
          console.log('i am an error');
      }else{
          console.log('I am the hash', hash);
          return hash;
      }
  }).
}

let butt = new Promise(function(resolve, reject) {
  bcrypt.hash(password, null, null, function(err,hash){

      if(err){
          reject(err);
      }else{
          resolve(hash);
      }
  }).
});

butt.then(function(hash){
  console.log('you will make it to the promise stage now', hash);
});
What this is doing is calling the constructor for Promise with a callback, that callback gives you two arguments that are functions/callbacks: resolve and reject. Inside the first callback (with arguments resolve, reject) you run your async code and when the async process is done you call resolve on success, reject on failure. The constructor for the Promise returns a promise that will be resolved by the resolve and reject inside your callback to it (function(resolve, reject){}) and resolve the .then().catch() chain as you're expecting.

Either use bluebird/Q's automatic method or make a wrapper that lets you create these Promise-ified calls so you only do this once and just keep calling the wrapped function instead of repeating this process.

edit: Also this brcrypt-nodejs library looks kind of shady, it's only version 0.0.3 and was last updated last year. There will probably be a better implementation of bcrypt for you somewhere.

edit: Oh whoops I didn't notice you were already promise-ifying it with bluebird. When you call promisify with bluebird it converts the function from one that takes a callback to one that doesn't, so just drop the callback and it should probably work I would think.

piratepilates fucked around with this message at 05:30 on Feb 2, 2016

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

piratepilates posted:

Either use bluebird/Q's automatic method or make a wrapper that lets you create these Promise-ified calls so you only do this once and just keep calling the wrapped function instead of repeating this process.


Am I not already? I was under the impression that my

Promise.promisify(bcrypt.hash);

was taking care of that for me.

Eugh, I need to read so much more about promises.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Raskolnikov2089 posted:

Am I not already? I was under the impression that my

Promise.promisify(bcrypt.hash);

was taking care of that for me.

Eugh, I need to read so much more about promises.

I didn't get enough sleep and read too little of that.

Anyway your problem is that bluebird.promisify() returns a new function that creates a promise, it doesn't edit the function in place.

I have this running locally and verified that it works:

code:
var Promise = require('bluebird');
var bcrypt = require('bcrypt-nodejs');
var promiseHash = Promise.promisify(bcrypt.hash);


hashPassword = function(password){
  promiseHash(password, null, null).then(function(res){
    console.log('did you even make it to the promise stage?', res);
  })
}

hashPassword('balls');

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

quote:

edit: Oh whoops I didn't notice you were already promise-ifying it with bluebird. When you call promisify with bluebird it converts the function from one that takes a callback to one that doesn't, so just drop the callback and it should probably work I would think.

Sadly not :( Now it tells me Unhandled rejection Error: No callback function was given. I even tried passing "null" 4 times since it seems to want 4 parameters.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

piratepilates posted:

I didn't get enough sleep and read too little of that.

Anyway your problem is that bluebird.promisify() returns a new function that creates a promise, it doesn't edit the function in place.

I have this running locally and verified that it works:

code:
var Promise = require('bluebird');
var bcrypt = require('bcrypt-nodejs');
var promiseHash = Promise.promisify(bcrypt.hash);


hashPassword = function(password){
  promiseHash(password, null, null).then(function(res){
    console.log('did you even make it to the promise stage?', res);
  })
}

hashPassword('balls');

You are a God among programmers. The amount of time I spent hitting that wall over and over. Thank you so very much.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Raskolnikov2089 posted:

You are a God among programmers. The amount of time I spent hitting that wall over and over. Thank you so very much.

Well it only took me three tries to actually understand the problem instead of jumping to conclusions about your post.



IN OTHER NEWS: Does anyone know anything about TypeScript+React? Why does the TS definition in React seem to want me to set every property in a component's 'state' when setState is called? As far as I know that's not the actual signature for setState and seems less readable making me have to explicitly call setState with properties that haven't changed.

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

piratepilates posted:

Well it only took me three tries to actually understand the problem instead of jumping to conclusions about your post.



IN OTHER NEWS: Does anyone know anything about TypeScript+React? Why does the TS definition in React seem to want me to set every property in a component's 'state' when setState is called? As far as I know that's not the actual signature for setState and seems less readable making me have to explicitly call setState with properties that haven't changed.

Have you tried using getters/setters?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Subjunctive posted:

It's been done, and it can be better, but thunking into the privileged library has cost as well. They can be redefined by script code as well, so you need to get the sharing right. Compared to inlining the statements in a loop directly, it's always going to lose at least by a bit. Nobody I know of does inter-procedural LICM or such, though maybe that's changed if things are being inlined aggressively enough. I should check.

Most arrays are small, though, so it really doesn't matter that there's more overhead. If you're walking a 10K buffer, speak with your profiler.

Actually, I looked it up. Array.prototype.forEach has been self-hosted in SpiderMonkey in JS since mid-2012:

https://github.com/mozilla/gecko-dev/commit/aae89c91b3f2fcd2120b44b9ca4012529af7dacc

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Suspicious Dish posted:

Actually, I looked it up. Array.prototype.forEach has been self-hosted in SpiderMonkey in JS since mid-2012:

https://github.com/mozilla/gecko-dev/commit/aae89c91b3f2fcd2120b44b9ca4012529af7dacc

Yeah, where the callback can be inlined it's a big win. Where it can't it's still a win, but will lose to the naive loop.

E: oh! They figure out the cross-compartment thunk, and how to do partial self-hosting without a perf hit. Clever!

Subjunctive fucked around with this message at 08:45 on Feb 3, 2016

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Also I'm surprised FF still has Array generics around, considering what a non-idea they are. I thought they were removed, but features like that never die I suppose.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

They let you run the operations over Array-likes that aren't really Arrays, such as strings, Arguments, HTMLCollection. Also defense against ad-hoc properties on the array collection dung with the function, but that's less important.

Adbot
ADBOT LOVES YOU

ModeSix
Mar 14, 2009

So I am doing an online course learning javascript, and one of the assignments is using DOM to add elements to a page.

I am getting an error when I load the page "Uncaught TypeError: Cannot read properly 'appendChild' of null".

I have the script waiting for the onload before executing.

Please help, this doesn't make any sense to me why this isn't working.



http://pastebin.com/m833DMJJ

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