<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: AlexMcD-git</title>
    <description>The latest articles on DEV Community by AlexMcD-git (@alexmcdgit).</description>
    <link>https://dev.to/alexmcdgit</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F851398%2F1af510c7-9234-4bae-a041-5fd354d4dcfc.png</url>
      <title>DEV Community: AlexMcD-git</title>
      <link>https://dev.to/alexmcdgit</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/alexmcdgit"/>
    <language>en</language>
    <item>
      <title>Recursive Fetching In Javascript</title>
      <dc:creator>AlexMcD-git</dc:creator>
      <pubDate>Sat, 14 Jan 2023 04:28:19 +0000</pubDate>
      <link>https://dev.to/alexmcdgit/recursive-fetching-in-javascript-4f0b</link>
      <guid>https://dev.to/alexmcdgit/recursive-fetching-in-javascript-4f0b</guid>
      <description>&lt;p&gt;For my latest project, I am working on finding degrees of separation between a given player, and the top ranked group, known as "Challenger"(which consists of the top 200) in the game League of Legends. All of this is made possible by the &lt;a href="https://developer.riotgames.com/"&gt;RiotAPI&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The process I had in mind was to look up other players from the 10 most recent games, find the highest ranked player, and repeat the process with said player if they are not a "Challenger" rank. The basic structure of the process would be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findChallenger(playerID){
    //lookup recent games with playerID
    //lookup players from those games
    //find the rank information on those players
    //sort the players by rank
    if (highestRankedPlayer.tier!== "CHALLENGER"){
        findChallenger(highestRankedPlayer.id)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In order to implement this with data from the API, fetch requests need to be made. Not only that, but the data for each fetch is reliant on the data from the previous fetch. In order for this to work we need to made the 2nd fetch after the promise of the first is resolved, like so:&lt;br&gt;
(using "data1.url" as an example of how the data of the first fetch is necessary towards making the 2nd)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch(url1)
.then(response1=&amp;gt;response1.json())
.then(data1=&amp;gt;{
    fetch(data1.url)
    .then(response2=&amp;gt;response2.json()
    .then(data2=&amp;gt;/*process data2*/)
    }
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this manner I "nested" fetch requests in order to reach all the API endpoints necessary for the functionality of my project on github &lt;a href="https://github.com/AlexMcD-git/lol-degrees-of-separation"&gt;here&lt;/a&gt;, and the specifics of making these calls are available on &lt;a href="https://github.com/AlexMcD-git/lol-degrees-of-separation/blob/main/client/src/components/SummonerForm.js"&gt;this&lt;/a&gt; particular file. The particular point of recursion is where, within "findChallenger(){}" (after the best player from your 10 most recent games is found)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (bestPlayer.tier ==="CHALLENGER"){
    return
}
else{
    summonerLookup(bestPlayer.summonerName)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I would recommend anyone looking to try out an API requiring authentication give the RiotAPI a go (being familiar with League of Legends, Valorant, or Legends of Runeterra is also helpful) due to the generous rate limits, intuitive end points, and ease of applying for an increase.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Dynamic Dropdown Selection Options for forms using React.js</title>
      <dc:creator>AlexMcD-git</dc:creator>
      <pubDate>Thu, 06 Oct 2022 01:46:25 +0000</pubDate>
      <link>https://dev.to/alexmcdgit/dynamic-dropdown-selection-options-for-forms-using-reactjs-43c3</link>
      <guid>https://dev.to/alexmcdgit/dynamic-dropdown-selection-options-for-forms-using-reactjs-43c3</guid>
      <description>&lt;p&gt;Drop down options on forms are an important aspect of the functionality of my react-redux/ruby on rails project, &lt;a href="https://www.runescape.com/"&gt;RuneScape &lt;/a&gt;themed task bingo, viewable &lt;a href="https://runescape-bingo.herokuapp.com/"&gt;here&lt;/a&gt; (hosted on heroku). &lt;/p&gt;

&lt;p&gt;I found myself satisfied with the outcome and wanted to show how I built out the result starting at the HTML foundation up to dynamic use with react.&lt;br&gt;
Starting with the basics of a form. (just the "select" and "submit" parts for this example even though it had more inputs in the project)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return(
      &amp;lt;form&amp;gt;
        &amp;lt;label&amp;gt;Which team are you submitting for? &amp;lt;/label&amp;gt;
        &amp;lt;select name="team"&amp;gt;
          &amp;lt;option&amp;gt;Select A Team&amp;lt;/option&amp;gt;
          {//teams need to populate as &amp;lt;option&amp;gt; tags}
        &amp;lt;/select&amp;gt;
        &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
      &amp;lt;/form&amp;gt;
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From there I would incorporate the react elements such as state and handling changes or submitting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [formState, setFormState] = useState(initialState)
function handleSubmit(e){
  e.preventDefault()
  //patch request to backend and reset form state
}
const handleChange = (e) =&amp;gt; {
    const { name, value } = e.target
    setFormState((prevState) =&amp;gt; ({...prevState, [name]: value}))
}
return(
      &amp;lt;form onSubmit={(e) =&amp;gt; handleSubmit(e)}&amp;gt;
        &amp;lt;label&amp;gt;Which team are you submitting for? &amp;lt;/label&amp;gt;
        &amp;lt;select name="team" value={formState.team} onChange={handleChange}&amp;gt;
          &amp;lt;option&amp;gt;Select A Team&amp;lt;/option&amp;gt;
          {//teams need to populate as &amp;lt;option&amp;gt; tags}
        &amp;lt;/select&amp;gt;
        &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
      &amp;lt;/form&amp;gt;
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have the basics of a form that will keep its contents in state and send a patch request when submitted. The remainder of the options come from the active "game" that is held in the redux store. We pull that into this component with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const activeGame = useSelector ((state) =&amp;gt; state.game.value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since our game object has a board array, each with the associated team, we can just use .map to create  components for each team to fill in the  tag.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        &amp;lt;select name="team" value={formState.team} onChange={handleChange}&amp;gt;
          &amp;lt;option&amp;gt;Select A Team&amp;lt;/option&amp;gt;
          {activeGame.boards.map(board =&amp;gt; &amp;lt;option key={board.team.id}&amp;gt;{board.team.team_name}&amp;lt;/option&amp;gt;)}
        &amp;lt;/select&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The intuitive nature of React made this fairly straightforward to do even after only a few months coding in javascript. If you have a different or better way of creating select options for forms please share below as I'm always looking to improve my own practices.&lt;/p&gt;

</description>
      <category>reactnative</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Serializers for your Serializers</title>
      <dc:creator>AlexMcD-git</dc:creator>
      <pubDate>Tue, 28 Jun 2022 23:15:20 +0000</pubDate>
      <link>https://dev.to/alexmcdgit/serializers-for-your-serializers-29h9</link>
      <guid>https://dev.to/alexmcdgit/serializers-for-your-serializers-29h9</guid>
      <description>&lt;p&gt;The last few weeks I was learning ruby on rails and was especially impressed by the powerful simplicity of serializers. For my example, I build an app for tracking experiments and chemical inventory for a lab group. Users can log in and create experiments and attach or remove chemicals to an experiment. Chemicals can also be created in the DB, have their amount edited, and be removed. For example, I can create an experiment with the description "Baking soda and vinegar volcano". For this I can add the existing chemicals, baking soda, and vinegar. Important to note that these chemicals could be part of multiple experiments at once, so the models are connected with a join table like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#/experiment.rb
class Experiment &amp;lt; ApplicationRecord
    has_many :chemical_experiments, dependent: :destroy
    has_many :chemicals, through: :chemical_experiments
    belongs_to :user

#/chemical.rb
class Chemical &amp;lt; ApplicationRecord
    has_many :chemical_experiments, dependent: :destroy
    has_many :experiments, through: :chemical_experiments

#/chemical_experiment.rb
class ChemicalExperiment &amp;lt; ApplicationRecord
  belongs_to :chemical
  belongs_to :experiment

#/user.rb
class User &amp;lt; ApplicationRecord
    has_many :experiments
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If I log out and then back in, I want to be able to fetch all of the user's data in one request, so that I can make use of React's responsive rendering with state. If set up the same :belongs_to and :has_many for user, experiments, and chemicals (the join table and through: is not needed in serializer if the models are set up correctly).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#/user_serializer.rb
class UserSerializer &amp;lt; ActiveModel::Serializer
  attributes :id, :username
  has_many :experiments

#/experiment_serializer.rb
class ExperimentSerializer &amp;lt; ActiveModel::Serializer
  attributes :id, :description, :is_complete
  has_many :chemicals

#/chemical_serializer.rb
class ChemicalSerializer &amp;lt; ActiveModel::Serializer
  attributes :id, :name, :amount_in_grams, :location
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, our user#show method (GET /user/:id) should return a user object with id, username, and an array of experiments. Each experiment object should return it's attributes and an array of chemical objects.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#/users_controller.rb
    def show
        user = User.find(params[:id])
        render json: current_user, status: 200
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fetching user with id of 1 would return something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "id": 1,
  "username": "Alex",
  "experiments": [
    {
      "id": 1,
      "description": "Baking soda and vinegar volcano",
      "is_complete": false
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The problem is that, by default, ActiveModel Serializer only will return one layer deep. In order to return the next layer, chemicals associated with the experiment, we need to make a slight change in our user_controller.rb.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#/users_controller.rb
    def show
        user = User.find(params[:id])
        render json: current_user, include: ['experiments', 'experiments.chemicals'], status: 200
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;with this slight change we have just a few lines of code split between a few files that builds our tree of data. What the fetch request should now return is the user with all of the nested data that we built serializers for.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "id": 1,
  "username": "Alex",
  "experiments": [
    {
      "id": 1,
      "description": "Baking soda and vinegar volcano",
      "is_complete": false,
      "chemicals": [
          {
              "id": 1,
              "name": "Acetic Acid",
              "amount_in_grams": 500,
              "location": "Acids Cabinet, Lab B"
          },
          {
              "id": 2,
              "name": "Sodium Bicarbonate",
              "amount_in_grams": 1000,
              "location": "Chemical Storage, Shelf 2"
          }
      ]
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This nicely structured data will make building out the front end much easier, especially in a framework like react. I hope other developers taking their first delve into ruby on rails will find some of this information useful.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>ruby</category>
      <category>rails</category>
      <category>activemodelserializers</category>
    </item>
    <item>
      <title>Algorithms Part 2 : A Beginner's Attempt (at improvement and translation)</title>
      <dc:creator>AlexMcD-git</dc:creator>
      <pubDate>Fri, 03 Jun 2022 02:39:24 +0000</pubDate>
      <link>https://dev.to/alexmcdgit/algorithms-part-2-a-beginners-attempt-at-improvement-and-translation-47mf</link>
      <guid>https://dev.to/alexmcdgit/algorithms-part-2-a-beginners-attempt-at-improvement-and-translation-47mf</guid>
      <description>&lt;p&gt;As mentioned in my &lt;a href="https://dev.to/alexmcdgit/algorithms-a-beginners-attempt-and-reflection-4e31"&gt;last post&lt;/a&gt;, I wanted to revisit the same problem after learning some ruby. Not only did I want to &lt;em&gt;"translate"&lt;/em&gt; from one language to another, I wanted to attempt at optimization. &lt;a href="https://replit.com/@AlexMcD-git/Algo-Practice-Problem-for-Blog#index.js"&gt;Here&lt;/a&gt; is my javascript solution. The full question is both in the repl and previous blog. &lt;/p&gt;

&lt;p&gt;The TL;DR is starting from an array of all false values, act upon it from an array of queries. First value of a query determines SET(1) or GET(2). SET means you turn the value in the starting array true, GET means you determine the position (indexing starts at 1) of the next true from the given starting position. SET has no output. If there are no ouputs for the GET, output is -1.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;testArray = [false, false, false, false, false]
queries = [[2, 3], [1, 2], [2, 1], [2, 3], [2, 2]]
expectedOutput = output = [-1, 2, -1, 2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I tried to recreate my javascript solution as similarly as possible using ruby methods as such.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;testArray = [false, false, false, false, false]
queries = [[2, 3], [1, 2], [2, 1], [2, 3], [2, 2]]
outputArray =[]

queries.each {|q| 
  if q[0]==1
    testArray[q[1]-1]=true
  elsif q[0]==2
    found = false
    i=q[1]-1
      until found || i&amp;gt;testArray.length do
        if testArray[i]
          outputArray&amp;lt;&amp;lt;i+1
          found = true
        end
        i=i+1
      end
    if found == false
      outputArray&amp;lt;&amp;lt;-1
    end
  end
}
print outputArray
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As mentioned before, this could run very long if the GET were to have to search a very long "testArray" only to return -1. What if setting also stored the value to an array of everything that has been set? I also had the idea to store the max value separately in case the "memoryArray" get large. First step is to chop down the "if GET" and store the SETs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;testArray = [false, false, false, false, false]
queries = [[2, 3], [1, 2], [2, 1], [2, 3], [2, 2]]
outputArray =[]
memoryArr=[]
memoryArrMax= 0

queries.each {|q| 
  if q[0]==1
    testArray[q[1]-1]=true
    memoryArr&amp;lt;&amp;lt;q[1]
    if q[1]&amp;gt;memoryArrMax
      memoryArrMax=q[1]
    end
  elsif q[0]==2
    if q[1] &amp;gt; memoryArrMax
      outputArray&amp;lt;&amp;lt;-1
    else
      puts 'i should be here 2 times'
    end
  end
}
print memoryArr
puts 
print outputArray
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;console:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i should be here 2 times
i should be here 2 times
[2]
[-1, -1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we see the output array is properly getting -1 twice, like before, but without even searching the the testArray. (I stored the max as a separate variable because the memoryArray could get pretty big, so in the worst case the &lt;em&gt;.max&lt;/em&gt; built in method would take longer to recalculate every time there is a GET, I'm guessing, as opposed to a single comparison with each SET).&lt;/p&gt;

&lt;p&gt;Next we add what to do if we have a GET where we know the return should not be -1. We need to find the first VALUE in memoryArray (which corresponds to indexes of true values in testArray) that is greater than or equal to the index provided with our GET request. This requires the array to be sorted. To cut down on sorting, we can opt to only sort on a GET request, instead of after every SET. Additionally, this can further be reduced by not sorting with consecutive GETs. I will add a boolean to track if our last query was a GET. This brings our final solution to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;testArray = [false, false, false, false, false]
queries = [[2, 3], [1, 2], [2, 1], [2, 3], [2, 2]]
outputArray =[]
memoryArr=[]
memoryArrMax= 0
lastWasGet=false

queries.each {|q| 
  if q[0]==1
    testArray[q[1]-1]=true
    lastWasGet=false
    memoryArr&amp;lt;&amp;lt;q[1]
    if q[1]&amp;gt;memoryArrMax
      memoryArrMax=q[1]
    end
  elsif q[0]==2
    if q[1] &amp;gt; memoryArrMax
      outputArray&amp;lt;&amp;lt;-1
    else
      if !lastWasGet
        memoryArr=memoryArr.sort
        lastWasGet=true
      end
      for index in memoryArr do
        if index&amp;gt;=q[1]
          outputArray&amp;lt;&amp;lt;index
        end
        break if index&amp;gt;=q[1]
      end
    end
  end
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Repl &lt;a href="https://replit.com/@AlexMcD-git/Algo-Rework-for-Blog#main.rb"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I understand that there may be some limitations of the .sort method that may make this solution also sub-optimal. I still don't think it could be worse than the worst case of the previous brute-force-y solution. If you made it this far, let me know what your think, and how you would approach this!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Algorithms : A Beginner's Attempt and Reflection</title>
      <dc:creator>AlexMcD-git</dc:creator>
      <pubDate>Fri, 13 May 2022 17:48:30 +0000</pubDate>
      <link>https://dev.to/alexmcdgit/algorithms-a-beginners-attempt-and-reflection-4e31</link>
      <guid>https://dev.to/alexmcdgit/algorithms-a-beginners-attempt-and-reflection-4e31</guid>
      <description>&lt;p&gt;As someone new to algorithm problems, seeing a big paragraph of words for a math problem can seem kind of intimidating. Here's an example of such a problem I came across only a week into practicing much simpler problems. Feel free to take a crack at it before having a look at my process:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Answer a Query&lt;br&gt;
Imagine a length-N array of booleans, initially all false. Over time, some values are set to true, and at various points in time you would like to find the location of the nearest true to the right of given indices.&lt;br&gt;
You will receive Q queries, each of which has a type and a value. SET queries have type = 1 and GET queries have type = 2.&lt;br&gt;
When you receive a SET query, the value of the query denotes an index in the array that is set to true. Note that these indices start at 1. When you receive a GET query, you must return the smallest index that contains a true value that is greater than or equal to the given index, or -1 if no such index exists.&lt;br&gt;
Input&lt;br&gt;
A list of Q queries, formatted as [type, index] where type is either 1 or 2, and index is &amp;lt;= N&lt;br&gt;
1 &amp;lt;= N &amp;lt;= 1,000,000,000&lt;br&gt;
1 &amp;lt;= Q &amp;lt;= 500,000&lt;/p&gt;

&lt;p&gt;Output&lt;br&gt;
Return an array containing the results of all GET queries. The result of queries[i] is the smallest index that contains a true value that is greater than or equal to i, or -1 if no index satisfies those conditions.&lt;br&gt;
Example&lt;br&gt;
N = 5&lt;br&gt;
Q = 5&lt;br&gt;
queries = [[2, 3], [1, 2], [2, 1], [2, 3], [2, 2]]&lt;br&gt;
output = [-1, 2, -1, 2]&lt;br&gt;
The initial state of the array is [false, false, false, false, false].&lt;br&gt;
The first query is GET 3, but no values in the array are true, so the answer is -1.&lt;br&gt;
The second query is SET 2, so the value at index 2 is set to true.&lt;br&gt;
The new state of the array is [false, true, false, false, false].&lt;br&gt;
The third query is GET 1, and the index of the true value nearest to 1 (to the right) is 2.&lt;br&gt;
The fourth query is GET 3, but no values to the right of index 3 are true.&lt;br&gt;
The fifth query is GET 2, and the value at index 2 is true.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If, like me, you're new to problems like this, it can be hard to decide where the code for something like this would even start. When lost, I find it easiest to verbalize the needs of the problem before coding them. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Input is two arrays, one starts out always the same (repeating array of "false", initially) and the other one, "queries", performs the operations to give us the output array.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The output array is correlated to the "queries" array, but doesn't have to match it in length.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;We perform one of two actions based on the first value of a query.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This seemed like enough to get started, so lets begin with setup. with two arrays and a function that "SETs" or "GETs". Since our output doesn't directly match anything we will start empty and add to it in our function:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const queries = [[2, 3], [1, 2], [2, 1], [2, 3], [2, 2]]&lt;br&gt;
const testArray = [false, false, false, false, false]&lt;br&gt;
const outputArray =[]&lt;br&gt;
queries.forEach(element=&amp;gt;setOrGet(element))&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;So we have the beginning and endpoint. setOrGet needs to look at the first element of the inner array for the two separate actions&lt;/p&gt;

&lt;p&gt;&lt;code&gt;function setOrGet(innerArray){&lt;br&gt;
  if (innerArray[0] === 1){&lt;br&gt;
    //do one thing&lt;br&gt;
    }&lt;br&gt;
  if (innerArray[0] === 2){&lt;br&gt;
    //do the other thing&lt;br&gt;
    }}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We have to be careful going forward because the problem mentions:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note that these indices start at 1.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But javascript array indexing begins at 0, so we always need to subtract 1 from the index provided. Now to add the "set" functionality, when the first element is equal to 1.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;function setOrGet(innerArray){&lt;br&gt;
  if (innerArray[0] === 1){&lt;br&gt;
        testArray[innerArray[1]-1]= true&lt;br&gt;
    }&lt;br&gt;
  if (innerArray[0] === 2){&lt;br&gt;
      findNextTrue(innerArray[1]-1,testArray)&lt;br&gt;
    }}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In order to keep setOrGet concise, I made a separate function for "GET", where we are finding the next element that reads true. To do this we pass the element that we start at, and the array we are searching. I used a &lt;em&gt;for&lt;/em&gt; loop, starting at the element, checking each for true. When a true is found I &lt;em&gt;push&lt;/em&gt; the index (+1) to the output (we also &lt;em&gt;return&lt;/em&gt; to break the loop and avoid pushing further elements). If no true is found, -1 is added instead.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;function findNextTrue(start, array){&lt;br&gt;
  for(index = start; index&amp;lt;array.length;index++){&lt;br&gt;
    if (array[index]){&lt;br&gt;
      outputArray.push(index+1)&lt;br&gt;
      return&lt;br&gt;
    }&lt;br&gt;
  }&lt;br&gt;
  outputArray.push(-1)&lt;br&gt;
}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;And it works! Full solution can be seen &lt;a href="https://replit.com/@AlexMcD-git/Algo-Practice-Problem-for-Blog#index.js"&gt;here&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;But can it be better?&lt;/em&gt; In this first go at the problem, the worst case scenario would repeatedly iterate over the entire N-length array of booleans, that can be up to a billion entries long. If _queries _is the maximum of 500,000 and every query is GET1, denoted as [2,1], this solution will take 5E14 operations (since without any SET operations, it will iterate all 1 billion items 500,000 times). Writing out this blog and explaining my process has already had me thinking about more efficient ways to handle this. Perhaps we have some way to keep track of where the true values are outside of the array of booleans. It is nice to see how my though process evolves in as little of a time that it has been since I started javascript 6 weeks ago (and algo problems 3 weeks ago), so this will definitely be something I revisit.&lt;/p&gt;

&lt;p&gt;I do want my fellow beginners to keep in mind that reaching a point where it works at all is the first step before optimization.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>"this" and the DOM</title>
      <dc:creator>AlexMcD-git</dc:creator>
      <pubDate>Fri, 22 Apr 2022 15:40:06 +0000</pubDate>
      <link>https://dev.to/alexmcdgit/this-and-the-dom-1k6j</link>
      <guid>https://dev.to/alexmcdgit/this-and-the-dom-1k6j</guid>
      <description>&lt;p&gt;Hello world,&lt;/p&gt;

&lt;p&gt;As someone with just under 3 weeks of experience with each of javascript, HTML, and css, I've found a couple things that seemed to work together very well. While surely not the first to do so, I couldn't find much information about it (probably because I'm not well versed enough in the lingo to Google it properly).&lt;/p&gt;

&lt;p&gt;The problem, like for many beginners, starts with an array or object that itself is full of objects, some of which have their own arrays or objects. I would like to iterate through this array and add that content to the DOM. Easy enough with "forEach" and a separate function for "rendering" each of them to the DOM.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arrayOfObjects = [{stuff}, ...,{the last of the stuff}]
arrayOfObjects.forEach(renderFunction)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since just looking at things is boring, I'd like to add some interactivity through event listeners. The basic breakdown is "I want to display something. I want to add an input of some kind. Input will change what is displayed". Now, to be less abstract I am going to move over to my specific example, but first a bare minimum background so anyone can understand.&lt;/p&gt;

&lt;p&gt;I want to render the stats for the characters (also known as "champions") of "League of Legends". Understanding the gameplay is completely unrelated here. Each character has health, attack damage, armor, and many other stats. Every time you level up those stats increase. The starting number and increase per level is different for every character. Our input will be a slider, from 1(starting level) to 18(max level). The goal here is to update the displayed stat as the slider moves. For example: &lt;em&gt;Character&lt;/em&gt; has 500 health at level 1 and 100 health per level up. Moving the slider to 6 means the character has leveled up 5 times, so their health stat should display 1000.&lt;/p&gt;

&lt;p&gt;For over 150 Champions this is a lot of data to display. So we instead show a thumbnail for each character and clicking it will load the details at the top. Here on out, I will try to keep the amount of code to a minimum, only sharing the most relevant details.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arrayOfObjects = [{stuff}, ...,{the last of the stuff}]
arrayOfObjects.forEach(renderFunction){
    //all the other stuff
    //setting the name of the character to the alt text of our image
    pic.alt = champion.id
    pic.addEventListener('click', clickChampionFunction)
}

const clickChampionFunction = (event)=&amp;gt;{
    //accessing the correct champion object, by the name(aka id)
    const featuredObject = championsObj[event.target.alt]
    statsListFeatured.innerHTML = statsRender(featuredObject.stats, 1)
}

function statsRender(statsObj, level){
    return `(string with a lot of interpolation that makes the data pretty)`
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Some rudimentary styling later, we can see our champion, base stats on the left side of the picture, and per-level stats on the right. Great!&lt;br&gt;
 &lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhuqdo2gsw04319yykuzv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhuqdo2gsw04319yykuzv.png" alt="Clicking a champion renders a bigger picture with stats"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we just need to add an event listener that puts in the slider's value as the level.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    //still inside of clickChampionFunction()
    levelSlider = document.createElement('form')
    levelSlider.innerHTML = `&amp;lt;input type="range" min="1" max="18" value="1"&amp;gt;`
    levelSlider.addEventListener('input', updateValue)
}

function updateValue(event){
  levelDisplay.textContent = `Level: ${event.target.value}`
  document.querySelector(`.baseStats`).innerHTML = statsRender(featuredObject.stats, event.target.value)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All good, right? No. Even though the &lt;em&gt;updateValue&lt;/em&gt; function, as of now, is only called within a block of code that has access to &lt;em&gt;featuredObject&lt;/em&gt;, the &lt;em&gt;updateValue&lt;/em&gt; function does not have access to that object. Since &lt;em&gt;updateValue&lt;/em&gt; is not within the scope of the  &lt;em&gt;clickChampionFunction&lt;/em&gt; it cannot access the variable. This took a good bit of thinking (and console.log-ing to realize) the first time. So, how do we pass parameters through an event listener callback? This seems to be an old question that was also asked on stackoverflow over &lt;a href="https://stackoverflow.com/questions/256754/how-to-pass-arguments-to-addeventlistener-listener-function" rel="noopener noreferrer"&gt;13 years ago&lt;/a&gt;. I don't just want an answer, I want to know why. Luckily the comment "JavaScript is a prototype-oriented language, remember!" helped me get there.&lt;/p&gt;

&lt;p&gt;What does this mean? We can see what type of data we are working with to determine how we can use it.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9m3izv18fzum8azs3gw4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9m3izv18fzum8azs3gw4.png" alt="Google Chrome Console"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So of course, you can do object things with objects. Is it really that simple? Just set a key to a value that I want pass through?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;levelSlider.obj = featuredObject
console.log(levelSlider)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhqp4rrfko39nmn1nyvre.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhqp4rrfko39nmn1nyvre.png" alt="Hidden or not?"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Logging the object itself does not seem to reveal our data (only the DOM element), but calling levelSlider.obj will reveal the &lt;em&gt;invisible data&lt;/em&gt; hitching a ride on our object. On the MDN page for &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" rel="noopener noreferrer"&gt;&lt;em&gt;this&lt;/em&gt;&lt;/a&gt; we can see: &lt;br&gt;
"As a DOM event handler&lt;br&gt;
When a function is used as an event handler, its this is set to the element on which the listener is placed."&lt;br&gt;
So if &lt;code&gt;this&lt;/code&gt; is our slider, and our slider has the .obj, is it really as simple as this.obj?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function updateValue(event){
  console.log(this.obj)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmfmhq3yqjikga5udx3h3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmfmhq3yqjikga5udx3h3.png" alt="it is that simple!"&gt;&lt;/a&gt;&lt;br&gt;
Yes, everything seems to have clicked into place. A strange bit is that &lt;code&gt;this&lt;/code&gt; does not work for arrow functions. As MDN puts it, "Arrow functions don't provide their own &lt;em&gt;this&lt;/em&gt; binding"&lt;/p&gt;

&lt;p&gt;So to finish things up, lets look at our level, and update the stats to be correct for the slider-selected level.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function updateValue(event){
  levelDisplay.textContent = `Level: ${event.target.value}`
  document.querySelector(`.baseStats`).innerHTML = statsRender(this.obj.stats, event.target.value)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhxcztwq1tx39f4qnv7of.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhxcztwq1tx39f4qnv7of.gif" alt="Working Slider"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Not even a week later, this seems very obvious, but at the time this was a little bit of a breakthrough moment. &lt;/p&gt;

&lt;p&gt;The takeaway for my fellow beginners:&lt;br&gt;
To access data in an event listener callback function, first add that data to an &lt;em&gt;attribute&lt;/em&gt; of the same element that is getting the event listener. It can then be accessed any time the event listener is called with &lt;em&gt;this.attribute&lt;/em&gt;.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>dom</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
