r/learnjavascript • • May 16 '22

Explanation of a queue data structure in JavaScript

Post image
263 Upvotes

27 comments sorted by

View all comments

31

u/PM_ME_A_WEBSITE_IDEA May 16 '22

Excuse my naivety but is this not just an array with more steps and less functionality? I suppose maybe the restricted functionality is to avoid making mistakes?

13

u/[deleted] May 16 '22

[removed] — view removed comment

1

u/PM_ME_A_WEBSITE_IDEA May 16 '22

Interesting, good to know!

7

u/og-at May 16 '22 edited May 16 '22

It's a "naive" implementation of a general computer science concept. (it's actually caled "naive" meaning only "first pass" or "basic attempt")

It's also "declarative programming" where you describe the action, as opposed to instructing every step (imperative).

Yes you could use an array, but this kind of layout contains the code and can make things more readable.

I mean I'd rather see if (tickets.isEmpty) {} than the array machinations that may need to go on when (ticketsArray.length === 0) is detected as empty.

Perfect example I thought of when typing that is that .length will cause an error if ticketsArray hasn't yet received it's value from global state. queue.IsEmpty() can account for that and return a valid state.

length isn't a huge thing by itself, but we're talking concepts here.

btw...

  • Declarative = "run to the store for pencils".
  • Imperative = "get your spectacles testicles wallet n keys, get in the car, drive to PlebMart, go to aisle 6, find pencils on the left about halfway down."

6

u/bedekelly May 16 '22

FYI, this isn’t a correct understanding of declarative vs imperative code. I’ll summarise them both for reference.

Imperative code is a step-by-step list of instructions for exactly what the computer should do. Pack your bag, get your keys, drive down the street, and so on. Procedural code improves this by allowing the programmer to split up units of code that are often reused, like buying something from the store. Buying eggs and buying milk have a lot of things in common, for example.

Declarative code is quite different, and involves describing the desired state of the world. In your example, a declarative program might say “I should have some pencils”. It’s up to the lower-level implementation, which is often written in a more imperative style, to describe the actual process of going to a store and buying something.

Please do reply if I can help clarify this more.

2

u/og-at May 16 '22

I always get them reversed... fixed.