0 votes
by (8.9k points)

I have an array called $npc.options.  I'm using the push() method to populate it at various points in the game.

I'd like the array to only ever contain unique values.  I guess I can use <<if>> statements like so:

<<if $npc.options.includes("attackPC")>>
  <<else>>
  <<set $npc.options.push("attackPC")>>
<</if>>

But is there a simpler way to do it?  Something like:

<<set $npc.options.uniquepush("attackPC")>>

 

1 Answer

+1 vote
by (68.6k points)
selected by
 
Best answer

First.  There's no reason to ever have an empty case.  Your initial code sample should be using the not operator.  For example:

<<if not $npc.options.includes("attackPC")>>
  <<set $npc.options.push("attackPC")>>
<</if>>

As far as a simpler way, you could use a Set instead of an Array.  Sets require that all members be unique—i.e. there can only be one such member.  For example:

/* Initializing $npc.options as a Set. */
<<set $npc.options to new Set()>>

/* Adding a member to the Set. */
<<run $npc.options.add("attackPC")>>

/* Removing a member from the Set. */
<<run $npc.options.delete("attackPC")>>

/* Checking for the existence of a member. */
<<if $npc.options.has("attackPC")>> ...attackPC exists... <</if>>

/* Checking for the non-existence of a member. */
<<if not $npc.options.has("attackPC")>> ...attackPC does not exist... <</if>>

 

by (8.9k points)
Thanks Exile, both for the advice on Sets and the not operator.  :-)
...