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
stoops
Jun 11, 2001
I have an array that looks like this:

n_88: {id: "n_88", type: "range"},
n_39: {id: "n_39", type: "file"},
n_42: {id: "n_42", type: "standard"}

If i have the index (n_39 or n_42 or n_88), how can i remove that from this array?

I tried to use splice, but it says array.splice is not a function.

Any help is appreciated.

Adbot
ADBOT LOVES YOU

Munkeymon
Aug 14, 2003

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



stoops posted:

I have an array that looks like this:

n_88: {id: "n_88", type: "range"},
n_39: {id: "n_39", type: "file"},
n_42: {id: "n_42", type: "standard"}

If i have the index (n_39 or n_42 or n_88), how can i remove that from this array?

I tried to use splice, but it says array.splice is not a function.

Any help is appreciated.

Are you sure it's not a plain object? It sounds like you have a plain object. If it is, you can just delete obj['n_39'];

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

stoops posted:

I have an array that looks like this:

n_88: {id: "n_88", type: "range"},
n_39: {id: "n_39", type: "file"},
n_42: {id: "n_42", type: "standard"}

If i have the index (n_39 or n_42 or n_88), how can i remove that from this array?

I tried to use splice, but it says array.splice is not a function.

Any help is appreciated.

You don't have an array, you have an object. Arrays in js do not / cannot have keys unlike other languages that have associative arrays or other structures like that. JS arrays have indexes, but they are positional. The syntax can be similar in that myArray[3] and myObject['myKey'] look similar, but they are different under the hood(ish)

Do what Munkeymoon said and you are all set.

Ranzear
Jul 25, 2013

Everything is an object in JS. The nomative 'array' you create with new is just an object with methods that work with numeric indexes which still kinda duck type as object properties. You can delete obj[n]; just the same as splicing it.

I eventually abandoned JS's idea of an array and stuck to bare objects once I figured that out, especially once I started using foreach instead of numeric iteration on sparse arrays. Should throw that in too: JS arrays are intrinsically sparse because it's just object properties, too, so assumptions about locality can be false as well.

Thermopyle
Jul 1, 2003

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

Tangentially related to the subject and spurred by a conversation with someone yesterday:

More people should use and be aware of the Map data structure in JS. You maybe should be using it instead of objects for key-value storage.

The one thing that sucks about Map is that there is no Map literal notation.

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

Thermopyle posted:

Tangentially related to the subject and spurred by a conversation with someone yesterday:

More people should use and be aware of the Map data structure in JS. You maybe should be using it instead of objects for key-value storage.

The one thing that sucks about Map is that there is no Map literal notation.

Hey, thanks for this! More people should be aware. This would have really helped on my last project.

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');`

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Thermopyle posted:

Tangentially related to the subject and spurred by a conversation with someone yesterday:

More people should use and be aware of the Map data structure in JS. You maybe should be using it instead of objects for key-value storage.

The one thing that sucks about Map is that there is no Map literal notation.

What is the advantage over object for the curious and lazy?

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Lumpy posted:

What is the advantage over object for the curious and lazy?

with objects,

-keys can clobber prototype methods
-keys can only be strings
-property/key order not guaranteed
-no foreach method
-have to use hasOwnProperty for existence check in case value is zero or null

Roadie
Jun 30, 2013
The one thing that's really infuriating about the native Map is that it, as befits the general insanity of JS, doesn't have a map method. You have to do a Map(whateverMap.entries().map()) instead.

Munkeymon
Aug 14, 2003

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



Bruegels Fuckbooks posted:

-property/key order not guaranteed

It is in some cases... because variety is the spice of life?https://stackoverflow.com/a/38218582/301807 is a good explanation.

This is definitely getting into good vs bad parts territory, though.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
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.

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

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.

You refer to them as 'object' 'Object' and '{}'. OMG Why is this so hard? It makes perfect sense...

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.

an skeleton
Apr 23, 2012

scowls @ u
Typescript question.

Oftentimes in apps, in my experience, you'll have an object type that represents the "completed" object, as in the object as it is accessed and unmarshalled from the database, and a "param" type, which are the necessary params to "send off" i.e. POST to the API to create the object. (Please correct me to what you feel is more correct terminology)

So, extremely simple example, type Apple might look like this:
code:
{
   ID: number,
  color: string,
}
whereas AppleParams (representing what you POST to e.g. "/api/apples") might just be like:
code:
{
  color: string,
}
Is there a super efficient way to handle maintaining these types in your typing? Do you just have a single type Apple where ID is optional? Do you simply maintain the two separate types? This starts to touch on validation issues and such as well. Just looking for thoughts here.

an skeleton fucked around with this message at 09:48 on Feb 20, 2018

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

an skeleton posted:

Typescript question.

Oftentimes in apps, in my experience, you'll have an object type that represents the "completed" object, as in the object as it is accessed and unmarshalled from the database, and a "param" type, which are the necessary params to "send off" i.e. POST to the API to create the object. (Please correct me to what you feel is more correct terminology)
Redux with TypeScript does this as well in the class declarations when you try to incorporate it with React for getting component props and state inputs.

quote:

So, extremely simple example, type Apple might look like this:
code:
{
   ID: number,
  color: string,
}
whereas AppleParams (representing what you POST to e.g. "/api/apples") might just be like:
code:
{
  color: string,
}
Is there a super efficient way to handle maintaining these types in your typing? Do you just have a single type Apple where ID is optional? Do you simply maintain the two separate types? This starts to touch on validation issues and such as well. Just looking for thoughts here.

What I do, and this is probably stupid and inefficient because I am dumb and bad, is make something like a "ClassName_Query" type that extends the Params type and a "ClassName_Params" type for what I expect to get from the thing. Usually I find that it's alright to make them be the same type ultimately, but whenever I try to add stuff later I find it's best to make them different.

Sorry if I misunderstood or if my advice sucks.

smackfu
Jun 7, 2004

Sounds like you could use a Partial here?

https://netbasal.com/getting-to-know-the-partial-type-in-typescript-ecfcfbc87cb6

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. ^^

Sedro
Dec 31, 2008

an skeleton posted:

Typescript question.

Oftentimes in apps, in my experience, you'll have an object type that represents the "completed" object, as in the object as it is accessed and unmarshalled from the database, and a "param" type, which are the necessary params to "send off" i.e. POST to the API to create the object. (Please correct me to what you feel is more correct terminology)

So, extremely simple example, type Apple might look like this:
code:
{
   ID: number,
  color: string,
}
whereas AppleParams (representing what you POST to e.g. "/api/apples") might just be like:
code:
{
  color: string,
}
Is there a super efficient way to handle maintaining these types in your typing? Do you just have a single type Apple where ID is optional? Do you simply maintain the two separate types? This starts to touch on validation issues and such as well. Just looking for thoughts here.

TypeScript code:
interface AppleParams {
  color: string;
}
type Apple = AppleParams & { ID: number };

function createApple(params: AppleParams): Promise<Apple> {
  ...
}

an skeleton
Apr 23, 2012

scowls @ u
Thanks! Great answers, exactly what I was looking for.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I have a bunch of different Typescript classes with differently shaped data, where data will be user-supplied, stored in a CouchDB database, and objects hydrate from the db at run-time.

code:
ClassA {
	props: {
		namedProperty1: string
		namedProperty2: number
	}
}

ClassB {
	props: {
		onlyProperty: string
	}
}

...
I'm not sure how to shape the data in CouchDB. In particular, I don't know how to label the data as being of type ClassA, ClassB, etc. One idea is to put the class names themselves in the data, which will break if the classes are renamed in a refactor.

Any suggestions? I'm really unsure of how to structure data in general in this kind of document database. It seems natural to store all of my instances of ClassA as an array in a ClassA document, but then I won't be able to refer to specific instances with something resembling a primary key (which is something I want to do).

Newf fucked around with this message at 20:40 on Feb 25, 2018

fantastic in plastic
Jun 15, 2007

The Socialist Workers Party's newspaper proved to be a tough sell to downtown businessmen.
Is there a list of common front-end JS interview questions? I have an upcoming interview and haven't touched front-end in a year, I could use a quick refresher.

geeves
Sep 16, 2004

Newf posted:

Any suggestions?

If you use 2-space indents instead of 8-space indents it does not take up up as much space and it scales better.

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" }
    }
}

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

geeves posted:

If you use 2-space indents instead of 8-space indents it does not take up up as much space and it scales better.


Nolgthorn posted:

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.

:arghfist:

More substantive reply to follow, Wednesday maybe.

Faith For Two
Aug 27, 2015
I'm adding some features to a chrome extension my company uses, and I'm wondering how to make the extension do/display display different things when you click the icon, depending on what website you're on.

Right now it displays an index.html file when you click the icon.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

Faith For Two posted:

I'm adding some features to a chrome extension my company uses, and I'm wondering how to make the extension do/display display different things when you click the icon, depending on what website you're on.

Right now it displays an index.html file when you click the icon.

I don’t know anything about chrome extension development but....

JavaScript code:
if(location === ‘google.com’){
    render <p>hello world</p>
}
else{
   render <p>hello something else</p>
}
?

teen phone cutie fucked around with this message at 12:52 on Mar 2, 2018

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen

Faith For Two posted:

I'm adding some features to a chrome extension my company uses, and I'm wondering how to make the extension do/display display different things when you click the icon, depending on what website you're on.

Right now it displays an index.html file when you click the icon.

If the extension has the activeTab permission then it can call the chrome.tabs.getCurrent API to get the info on the tab from within the context of the index.html page.

Alternatively, the current tab's data info object is passed into programmatically assigned callbacks, i.e.
code:
// Change to chrome.pageAction if your extension only activates for specific pages.
chrome.browserAction.onClicked.addListener(function (tab) {
    console.log(tab);
    console.log(tab.url);
});

LP0 ON FIRE
Jan 25, 2006

beep boop
I've been working on my own little cellular automata thing, and I noticed something that keeps on happening. The left side eventually consists of straight horizontal lines of the same species (letter).



The project was recycled from a text animator project, so please excuse the excessive and poor on screen controls.
http://mysterysystem.com/stuff/ALifeX/ALifeX.html

You can reproduce this more quickly by going to the page, moving the slider all the way to the left for the fastest cell speed, then clicking in the grey area hopefully to start a never ending chain reaction which will eventually recreate the "problem" of having horizontal lines of species on the left side.

Or you can just go here to see it already in this kind of state: http://mysterysystem.com/stuff/ALif...l33/f1/r5ZFqg==

I'm wondering if I'm doing something weird like copying objects wrong or having each cell do checks oddly that causes this to happen. I haven't been able to figure it out so far.

LP0 ON FIRE fucked around with this message at 19:38 on Mar 5, 2018

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?
First of all, give your variables proper names. One character names isn't going to cut it.

Second, you're mutating values in the grid as you scan through it. This creates a bias in a particular direction. New cells created on one side of the current cell will see an update on the same generation they are created on, while those on the other side will have to wait until the next generation. The quicker update rate amplifies this issue. At the worst, as the update scans across a row, each cell births a new cell which is immediately scanned and births a new cell, etc., etc.

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

Yeah basically you need to separate out each step or generation of the automata. I'd say use a double buffer of board states; read from one write to the other, then swap roles next step, etc.

e: To drive the point home a little further: a half processed board is not a valid state for an automata to be in. Its only valid at the distinct generational steps. As soon as you update one cell, the remainder of the cells to be processed are getting whats known as "dirty reads", because it now has a value from a future state.

peepsalot fucked around with this message at 20:32 on Mar 5, 2018

LP0 ON FIRE
Jan 25, 2006

beep boop
Thank you I was thinking it would be something like that. Unfortunately my brain has trouble grasping how that works and I'll really need to tinker with it to make it operate correctly. If it's happening here, I'm guessing I'd be having the same problem if I did this with Conway's Game of Life.

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?
I should mention a more fundamental issue. If you go look at the rules for Game of Life you'll see that each cell's state in the next generation is a function of the state of it and it's neighbors in the current generation. As long as the programmer is careful to not update cell states on the fly while scanning (a mistake probably made by everyone who's tried to code up game of life on their first try), there is no dependence on the direction in which the grid is scanned.

However your thing has cells setting the state of their neighbors. The problem with that is it's always going to depend on the direction you scan the grid in. If two cells are going to update the state of a third cell, the final state of the third cell depends on which cell was scanned first. You need to write your rules so that a cell can compute it's next state based on it's neighbors' states. Then you scan through the grid computing the next state for each cell, then you take that to be the current state and repeat.

LP0 ON FIRE
Jan 25, 2006

beep boop
I think I understand but it sounds like it now needs to do a lot more work because every cell needs to check the state of the other cells and how they would effect the current. Tough luck?

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer
Tough luck indeed. The easiest way to do such things is, as stated, to just have two instances of the world, one for the current point in time, and one for the next time step, which is generated one cell at a time based on the current world.

Then overwrite the current time step's world with the future one.

Ranzear
Jul 25, 2013

Osmosisch posted:

Then overwrite the current time step's world with the future one.

Or do no copy operations at all and, instead, just display the future step, then write the next step to the old frame.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Ranzear posted:

Or do no copy operations at all and, instead, just display the future step, then write the next step to the old frame.

Calculate all future steps and put them in an array so you can time travel through them with BLAZING FAST PERFORMANCE.

No, wait, that's a terrible idea. OR IS IT???

Roadie
Jun 30, 2013

Lumpy posted:

Calculate all future steps and put them in an array so you can time travel through them with BLAZING FAST PERFORMANCE.

No, wait, that's a terrible idea. OR IS IT???

Make sure to use webworkers for maximum performance.

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Roadie posted:

Make sure to use webworkers for maximum performance.

:bisonyes:

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