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
Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I want to build a node module that uses websockets and I want it to work on both the server and in the browser. On the server I'll need to require websockets but in the browser use the native implementation. Is there any way to do that? Does it require two builds? Maybe a required websocket parameter on instantiation passed by the user?

Adbot
ADBOT LOVES YOU

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Great now I don't care about building it.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
If the two were wildly different then I wouldn't be concerned about building a single library. Yawn. I'm working on a subprotocol implementation.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I decided to write a separate lib for the browser implementation anyway. Since just the build environment alone is so different, I noticed a lot of package maintainers do it this way regardless. I'm repeating a lot of code between the two, but the library isn't so huge it isn't that big a deal.

Essentially I have a src directory and a file in it that takes an argument like so:

code:
module.exports = function (WebSocket) {
    ...
};
Then I have an index.js file in the base directory that is like so:

code:
module.exports = require('./src/my-lib')(WebSocket);
That way I can grab the src file and use it with a mock WebSocket library in my tests. I think this works well but when I build I end up with essentially "double" IIFE, where I have a self executing function wrapping a self executing function. I don't think that's necessary.

Can't figure out how to tell my build environment to just spit it out as is without any additional stuff. I'm using rollup.js

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I trimmed it down a little bit using an es6 import/export in index.js

It bundles just fine into IIFE.

But now I wonder, if index.js is using es6 exports and the lib is using commonjs, can bundlers like Browserify and Webpack handle it. Something I've never thought about before, I suspect they can. I imagine all kinds of client side libraries use any combination.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Is there any alternative to using npmjs as a Javascript developer?

Is an alternative even possible since npm seems to come bundled with node. That feels like putting all our eggs in one basket. For an ecosystem especially that seems to pride itself on having a million different ways to render a checkbox.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
That's my understanding, yarn and others are just another layer at the client side.

I found this website http://node-modules.io/

It suggests hosting your own registry and pointing npm at it. There really is no alternative, is there.

Nolgthorn fucked around with this message at 21:15 on Feb 11, 2018

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I'm a fan of Set. `mySet.add('whatever');` is easier than `if (!myArr.includes('whatever')) myArr.push('whatever');`

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Dumb Lowtax posted:

I just picture key/value "objects" as hash tables and expect that lookup complexity is similar to a hash table. Are Maps any different in that respect?

Also is there anything besides "objects" we can call the curly brace structures, because all my code is laid out in classes and very object oriented and I use the word "object" all the time when describing class instances in my code, it gets so confusing.

I call class instances 'instances' and I call object literals 'objects'... man I hope you aren't using classes when they arguably aren't useful my code became so much cleaner when I stopped doing that. If I don't need an instance I don't make one.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
The object would all be verified on the server and what you're building the object out of you know to be valid. So I wouldn't build a structured object at all. I'd use type `Object`. I'd like TypeScript to add a type `pojo` or `json`.

`Partials` look really useful could be a solution as well. ^^

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
CouchDB is schemaless so you just have to be generally careful what you insert and then assume what you get back out of it.

If you want to store object types in the database there's nothing wrong with that but you should decouple the class names from the values you are storing. My suggestion is use a beautiful beautiful enum. Or a object like `{ 'classA': ClassA, 'classB': ClassB }`.

If you use 4 space indents instead of 8 then you'll still be able to grok what you're looking at without a widescreen monitor and be able to also see where you're got too much nesting. Wait a minute those are tabs.

Let me get my crucifix.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Also it's valid to do something in your data like:

code:
{
    "cats": {
        "0c410a9c-551f-4524-bc09-71c22d2631ee": { "name": "Tammy" },
        "c575bea0-9a8c-48f3-af64-513367dc7687": { "name": "Ruddigar" }
    },
    "dogs": {
        "b7103331-612a-4a2b-b262-d067f23afbe0": { "name": "Alf" },
        "097e085b-06ef-4d11-848f-72cbaaffb65c": { "name": "Bruno" }
    }
}

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Doom Mathematic posted:

$('.this-element-sure-as-heck-does-not-exist').click() just silently succeeding when it really, really would have been more helpful if it failed noisily.

In my last days with jQuery I would almost undo what it was doing.

code:
var ele = $('.this-element-sure-as-heck-does-not-exist');
if (ele[0]) {
    // etc
}

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I don't know if I'm helping or not but my experience is that Vanilla is the best Javascript environment of all time. If it's in node I don't have to compile anything, as few dependencies as absolutely humanly possible, no nothing, it's more or less zen. As zen as Javascript can be.

For frontend you have to build for es5, I prefer really strongly the simplest tools possible. So buble for basic es5 sans IIFE, and then rollup to put that es5 with es6 imports into a single file. If I'm doing the build step then there's no reason not to basically use Vue (or React) really. If it makes sense and I'm not just using a whole bunch of tools when it's not necessary.

Wish I could use Vue with buble/rollup instead of webpack or similar colossal monstrosities that do way more than necessary. :(

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I would say if you are compiling anyway you should compile for maximum compatibility, if there are no significant drawbacks to doing so.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Joda posted:

Don't you lose significant performance potentially? Also I assume there is no way to make wasm compatible with an ES5 platform
If you are building a video game in Javascript perhaps you should take performance into account. It might have an effect on performance. But modern computers, even really cheap ones can perform billions of operations per second, most of your processing is going to be consumed with draw calls.

Met somebody once, I was conducting their interview, and they wrote all of their loops in reverse.

code:
for (let i = 10; i >= 0; i--)
So I asked him why he was doing that, he said it was more performant. I tested it, and it wasn't. But even if it was, so what?

I can definitely appreciate having more performant applications. But you do that these days by limiting the number of dependencies you import, eliminate the bulk introduced by "general purpose" tooling. Don't write the code itself in weird ways for an imperceivable <0.1 ms performance boost.

Compiling to ES5 feels that way to me. There's no reason to be worried about reduced performance because of that alone, if there's performance gains to be made probably a good start is not using bootstrap for example. Or replacing javascript animations with css animations. Not using lodash' functional methods. Removing jQuery. That sort of thing.

Nolgthorn fucked around with this message at 20:09 on Dec 2, 2018

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Suspicious Dish posted:

I'm not joking when I say that in several of my projects, I replaced for(let foo of bar) with for(let i = 0; i < bar.length; i++) let foo = bar[i]; to a significant performance boost. This was after I profiled and saw it was an issue, and then fixed it.

This stuff matters, it really does. The compiler can often do a really crap job with some of this stuff.

Even faster calculate the length ahead of time

code:
const j = bar.length;
for(let i = 0; i < j; i++) {
    const foo = bar[i];
}
But true, for..of is notoriously slow. I cannot get enough of it.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Suspicious Dish posted:

I don't understand why anybody would willingly use Babel, for instance.

I really don't like Babel. An alternative is Buble, it has always made me happy. Typescript has a really cool compiler, makes great code output. But for some reason it doesn't allow you to compile directly to iife, at least not the last time I looked. So I used to combine it with a second build step using rollup, that worked really well.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I think my issue with Typescript is just that ES2015+ is really really good. It does whatever I need without types when I write my code cleanly. More than that, I spend a lot of my time in Node, which immediately means Typescript is not nearly so useful to me. I do not want to compile my code if I don't have to and in Node my code is always going to run the same way. When I transition to the client side, I have very little reason to context switch my programming language.

That's probably the biggest reason Node took off in popularity, because people didn't want to write in two languages.

The least important reason I don't want to use Typescript is because combining it with god knows what you really need, like Vue or a any number of front end technologies is more difficult than not doing it. The pain points aren't worth it unless I'm writing something exceedingly complicated. I'd rather just write explicit code across a large number of different files anyway.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Strong Sauce posted:

if you need to parse an array from string into a number.. why not just
code:
arrayOfIntStrings.map(Number)

That seems ambiguous. I prefer the explicit form.

code:
arrayOfIntStrings.map(num => parseInt(num, 10))

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
It's not entirely clear what it's doing.

code:
typeof Number('35')
"number"
typeof new Number('35')
"object"
What if you want to ensure it's an integer, or moreover, perform additional tests to ensure the value isn't undefined?

code:
Number()
0
Number('')
0
Number(undefined)
NaN
Would you prefer the first or second form of the following for example?

code:
arrayOfIntStrings.map(num => parseInt(num, 10));
arrayOfIntStrings.map(num => Math.floor(Number(num)));
So it's more extendable and therefore easier to read, because I know what was expected to come out of it when I read it again in 10 years.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Why does eslint "recommend" 2 space tabbing? Eslint's rules are insane based on that.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
4 space tabbing makes the depth and thus scope generally clearer. 2 spaces is one tiny char different from an actual space. 4 spaces helps disincentivise callback hell and thus promotes generally cleaner coding practices. It's easier to read. 4 spaces instead of two isn't best for all languages but I'd say it's dominant in Javascript for good reason.

Why isn't it the default?

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Well I'll be damned.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Here is what my screen looks like with a new file open that I'm working on for about 15 minutes. I have placed my first indented line, it's 4 spaces and it already looks practically cramped. I'm not sure how people can stand it being two spaces.

https://imgur.com/a/gN1D7Ld

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Thank god for insignificant whitespace so things like that are possible.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I (unpopularly) believe 4 spaces are better than 2 but I also think jQuery is stupid and much more complicated than vanilla js. It comes from a time when something was needed to enforce compatibility between browsers and has been obsolete for nearly a decade.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Are you sure you're designing something that needs webpack+typescript+npm? I imagine you are hitting yourself in the foot with a hammer because of all that tooling. WebRTC is just one of those things, the spec is designed by committee and so even though it's P2P you need like 2-5 intermediary or ancillary servers that do whatever.

I'm not convinced any of it is necessary, if I needed to do something with it I'd probably just pay for some service that provides it.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Tip posted:

That's disheartening, I'm about to start work on some new features that I planned to use WebRTC for... Maybe I'll just do it the old fashioned way instead.

I just spent forever fighting with the Web Audio API, which is a giant piece of poo poo with all kinds of weird limitations placed on it for no reason. Like, yeah, you can encode mp3s, but only in real time. And yeah, the api has most of the standard audio effects and filters, but it doesn't specify their implementation, so you get different results in every browser.

You sound like you're doing something I tried to do a while ago. I was streaming audio from the user to a server where the recording was saved. At that time the only thing you could reliably capture was WAV-like gigantic amounts of data. So then I needed to include a several mb js-compiled version of an Opus encoder on the page.

Then with the audio streaming into a compressed format I eventually gave up on WebRTC and decided on using websockets, breaking the audio up into chunks encoded as base64. None of it was ideal at all. But in the end it felt reasonably as good as I was going to get it.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

roomforthetuna posted:

Well no, it doesn't need all the things, but webpack doesn't work without some amount of npm, and typescript for a large project would suck without some sort of package wrapper, and webpack seems to be the only one that supports dynamic module loading which I want because my project is intended to be extensible, and I don't want it to have to load everything before anything works.

Not to tell you how to do it but I'd just compile separate js files as needed, then use the `async` html tag. Bingo bongo and it's done. The only thing typescript's compiler is bizarrely still missing is iife, so I use something lightweight like buble when I need it if I'm using typescript.

Webpack is like trying to land a rocket on mars, when all you really want is a little fin that's on the rocket. It has like 8 billion dependencies, it's a bloody mess.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Dominoes posted:

What method do you recommend for causing a long calculation to not block the main thread? I'm attempting to use async, but am likely doing it wrong. Case: Have some long validations that once complete, trigger a Redux update. What currently happens is the app hangs until they're done. Is there a way I can make the GUI run smoothly while the calc is being performed, and update the Redux state once complete? From what I've read, it appears that prepending the long funcs with 'async' should accomplish this. Don't need to return anything, just let Redux update the state once complete.

Javascript is still single threaded. Although you may async appropriately, if it's CPU heavy it will block the thread at whatever point that the stack decides to process it. What you may be looking for is web workers.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Yes, it's not a vue thing it's a javascript thing. The alternative is to do something like:

code:
this.debouncedSetFilters = _.debounce(() => {
    this.setFilters();
}, 3000);
or:

code:
this.setFilters = this.setFilters.bind(this);
this.debouncedSetFilters = _.debounce(this.setFilters, 3000);

Nolgthorn fucked around with this message at 00:17 on Jan 12, 2019

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I've started looking at technical interviews as a little window into what to expect at the company. Because generally you're going to be talking to leads on the project that are choosing new team members for themselves, they'll throw questions at you that try to get to the bottom of whether you can handle it. A recent interview they kept asking me question after question about bizarre Javascript language behaviours every single one of my answers started with "why would you ever write something like that?"

Turns out the entire tech stack is Javascript that was written ages ago by Java developers who seemed to just throw code at the runtime until it worked and then walked away. Every night now I dream about code I read the day before, like my brain is trying to work it out.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
https://www.codewars.com/

Is my favourite practice website, it proposes you a (often very) simple challenge. You solve it and then it compares you to everyone else's solution, you can vote up and down other people's solutions it's a little like a social network about code. I've found interviewers are happy when I mention it.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
If you want to learn something general and useful I recommend my favourite coding style --procedural--.

Which overall removes the need for state, while not needing to wade into the madness of functional programming. You get all of the same benefits of functional programming while also improving the readability of the code rather than devastating it. It's especially fantastic in Javascript because Javascript has a lot of really useful stuff in it that isn't purely functional in nature.

I see too many people bending over backwards trying to shoehorn the language into a functional style.

As an example of removing state:

code:
function createMyMethod(config) {
	return function myMethod(x, y, z) {
		console.log(config.foo);
	};
}
Can be more simply written, and tested, as such:

code:
function myMethod(config, x, y, z) {
	console.log(config.foo);
}

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I needed to run code on a schedule, for example at the top of every hour and I opted to use setTimeout instead. Calculating the time until the top of the hour and calculating again after I finished doing whatever I was doing. But if I didn't care, I can't imagine what's wrong with setInterval as long as you account for possible timeouts.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Don't get me wrong I love websockets. Websockets are the best thing ever and as soon as I have an excuse I'll use them. Like for example if the server ever needs to tell me anything. I'd take websockets over polling for sure.

The thing that's hard about them is maintaining the connection, detecting a lost connection, and managing requests that involve a response.

So a wrapper something like https://www.npmjs.com/package/passage-rpc

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Disclaimer: I wrote that ages ago. Nobody is downloading it. :( It works perfectly.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
The main focus of the library is RPC rather than maintaining connection, it's for client side apps especially single page apps that forego http entirely, I guess that isn't really popular yet. Maybe it's time I updated it and better the documentation.

Nolgthorn fucked around with this message at 17:00 on Jan 21, 2019

Adbot
ADBOT LOVES YOU

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
code:
const a = [[1, 2], [2, 3], [1, 2]];
Oooh a coding challenge.

code:
function findUniqueIndexes(arr) {
    const indexes = [];
    for (let i = 0; i < arr.length; i++) {
        if (arr.indexOf(arr[i]) === i) indexes.push(i);
    }
    return indexes;
}

function dedupeTuples(tuples) {
    const arr = tuples.map(tuple => tuple.join(','));
    const indexes = findUniqueIndexes(arr);

    return indexes.map(index => tuples[index]);
}

dedupeTuples(a);

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