<?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>Forem: aohibbard</title>
    <description>The latest articles on Forem by aohibbard (@aohibbard).</description>
    <link>https://forem.com/aohibbard</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%2F333538%2F08ce197a-555e-4c1c-b2a1-0d6ac03cc90b.png</url>
      <title>Forem: aohibbard</title>
      <link>https://forem.com/aohibbard</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/aohibbard"/>
    <language>en</language>
    <item>
      <title>Lemonade Change</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Sun, 29 Nov 2020 21:32:25 +0000</pubDate>
      <link>https://forem.com/aohibbard/lemonade-change-1fg4</link>
      <guid>https://forem.com/aohibbard/lemonade-change-1fg4</guid>
      <description>&lt;p&gt;It has been a food-filled few days so let's massage the brain with an easy post: how to solve Leetcode #860 &lt;a href="https://leetcode.com/problems/lemonade-change/"&gt;"Lemonade Change."&lt;/a&gt; In the problem, we are told that a lemonade costs $5, you the vendor have no change to start with, and buyers will pay with either a $5 bill, a $10 bill, or a $20 bill. Given an array of called &lt;code&gt;bills&lt;/code&gt; containing only 5, 10, or 20, determine if you can provide the appropriate change at every transaction. If so, return &lt;code&gt;true&lt;/code&gt;, if not, return &lt;code&gt;false.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This problem is a Leetcode easy, and under the spell of too many carbs, seemed difficult at first, but honestly it's not much harder than fizzbuzz. &lt;/p&gt;

&lt;p&gt;To start, let's deal with our edge cases. If we receive an empty array or the first value of the array is NOT equal to 5, we have to return false. In the latter case, we know that the seller does not have any change to start with, so any array that does not begin with 5 assumes change will be provided. That's impossible. So let's write that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var lemonadeChange = function(bills) {
  if (!bills.length || bills[0] !== 5) return false
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The next step is to figure out how to approach the problem. The approach requires us to iterate over the whole array and to compare values based on existing change. Effectively, we need to create a change drawer. I opted to do this as an object, where the keys correspond to the dollar amount of a bill and the values to the quantity of those bills: &lt;code&gt;let change = {'5': 0, '10': 0, '20': 0}&lt;/code&gt; (remember that integers cannot be used as keys in JavaScript). &lt;/p&gt;

&lt;p&gt;The next step is to consider all of the different scenarios and operate on our object accordingly. The function will iterate over the array, testing the input value against a series of if/else statements, each based on the value of the input.&lt;/p&gt;

&lt;p&gt;The first one is easy. If the array value is 5, there is no need to produce change, so we simply increment the '5' key in our change object. (NB: I did not do this, but because any array that does not begin with 5 will return false, we could theoretically initiate the change object with '5' have a value of one, and begin iterating at array index 1 to save a smidgeon of time).&lt;/p&gt;

&lt;p&gt;The second case requires us to address what happens if the array value is 10. In this case, we once again increment the appropriate value in the change object. But this time, we have to produce change. Given that there are only $5, $10, or $20 bills, we can only pay change with a $5 bill. If there is a $5 bill in the change object (that is, key 5 has a value greater than or equal to 1), we can produce change. So we have to decrement the value of the 5 key by one. If not, no change can be produced, so we should break the loop and return false.&lt;/p&gt;

&lt;p&gt;The most complicated logic comes with a $20 bill. We start the same one, by increment the value of key '20' by one and then seeing if change can be produced. Change can be produced with a $10 and a $5 or three $5 bills. Because $5 bills are more necessary, we should check if there is a $10 and a $5 first. If so, decrement the corresponding keys by one. If not, see if there are three $5 bills. If so, decrement key 5 by three. If neither condition is true, once again break the loop and return false, because a situation has been produced where no change is available. &lt;/p&gt;

&lt;p&gt;By inserting these &lt;code&gt;return false&lt;/code&gt; statements throughout the loop, we have addressed any situation where it is impossible to produce correct change. That means, if the loop successfully completes by iterating over all values in &lt;code&gt;bills&lt;/code&gt;, the return value must be true. &lt;/p&gt;

&lt;p&gt;Check out the full function below. It's a lot of logic but all in all, pretty simple.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var lemonadeChange = function(bills) {
  if (!bills.length || bills[0] !== 5) return false
  let change = {'5': 0, '10': 0, '20': 0}
  for(let i = 0; i &amp;lt; bills.length; i++){
      if(bills[i] === 5){
          change['5']++
      } else if (bills[i] === 10){
          change['10']++
          if (change['5'] === 0){
              return false
          } else {
              change['5']--
          }
      } else {
          change['20']++
          if (change['10'] &amp;gt;= 1 &amp;amp;&amp;amp; change['5'] &amp;gt;= 1){
              change['10']--
              change['5']--
          } else if (change['5'] &amp;gt;= 3){
              change['5'] -= 3
          } else {
              return false
          }
      }
  }
  return true
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>algorithms</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Manual Implementation of JSONPath</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Mon, 16 Nov 2020 11:55:18 +0000</pubDate>
      <link>https://forem.com/aohibbard/manual-implementation-of-jsonpath-550l</link>
      <guid>https://forem.com/aohibbard/manual-implementation-of-jsonpath-550l</guid>
      <description>&lt;p&gt;A few weeks ago, I was given a live coding challenge to write a function that would parse a pathway of a JSON object. The question was effectively a manual implementation of &lt;a href="https://jsonpath.com/"&gt;JSONPath&lt;/a&gt;. For the purposes of this post, we will work with this object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;json_obj = {
    “hello”: [
        “world”,
        {“hello”: true},
        [3, 4, 5]
    ],
    “world”: {
        “from”: “Your Friend”
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The idea is that if fed the &lt;code&gt;json_obj&lt;/code&gt; and a path, one would return the following results:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;get_json_value_by_path("$.hello[1].hello", json_obj) // true
get_json_value_by_path("$.world.from", json_obj) // “Your Friend”
get_json_value_by_path("$.hello[2][0]", json_obj) // 3
get_json_value_by_path("$.does.not[3].exist", json_obj) // “Key does not exist”
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I stumbled performing this in JavaScript, coming up with a very clumsy answer that relied on a lot of Googled Regex. But as it turns out, it is very easy to do in Python.&lt;/p&gt;

&lt;p&gt;In working with the object in Python, we need to ensure that we are treating the object as a JSON object. This means calling on Python’s native json capabilities by writing &lt;code&gt;import JSON&lt;/code&gt; at the top of the file. We then call on &lt;code&gt;json.dumps&lt;/code&gt; to serialize the object into JSON format and then &lt;code&gt;json.loads&lt;/code&gt; to support reading the JSON object in Python (this is similar to JSON.stringify and JSON.parse in JavaScript). &lt;/p&gt;

&lt;p&gt;For me, the challenge here is working with the index values in bracket. For the second example, which should return “Your Friend,” the function is just a matter of splitting and parsing the file path string and interpolating them in a for loop. To do this, we would call on our JSON function as above, and then split the path name string and the period, pulling out the terms we need. Because all of the path names begin with a dollar sign, we can ignore the value at index zero and then interpolate the path keys as needed. This would look like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_json_value_by_path(path, obj):
  json_dump = json.dumps(json_obj)
  data = json.loads(json_dump)
  paths = path.split('.')
  for i in range(1, len(paths)):
    data = data[str(paths[i])]
  print(data)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unfortunately, the index values are there. I’m fairly certain this is not the best solution, but my approach was to inspect every path value in the loop to see if contains numbers. To do this, we use the &lt;code&gt;findall&lt;/code&gt; function in python and check each string to see if it includes any numbers. If it does, these numbers are placed in a list called &lt;code&gt;res&lt;/code&gt;, and the existence of values in &lt;code&gt;res&lt;/code&gt; determines how we proceed. If it has a length of zero, we proceed as above, if not, we iterate over each of the indices in &lt;code&gt;res&lt;/code&gt;. I have also called upon a regex function to check if a value is a digit, which requires importing another library: &lt;code&gt;re&lt;/code&gt;. Note that I have also introduced a value called key in this loop. We have to work with the root string in the path first before we attend to index values. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;import re&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_json_value_by_path(path, obj):
  json_dump = json.dumps(json_obj)
  data = json.loads(json_dump)
  paths = path.split('.')
  for i in range(1, len(paths)):
    res = re.findall(r'\d+', paths[i])
    #if there are index values in the string
    if len(res) &amp;gt; 0:
      key = paths[i].split('[')[0]
      data = data[str(key)]
      for i in range(len(res)):
        idx = int(res[i])
        data = data[idx]
    else: 
      data = data[str(paths[i])]
  print(data)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The scalability of this solution is not great as the regex function assumes that all index values will be standalone, single value integers. We could easily modify this if needed by finding all numbers between brackets say, but it works for our test cases. &lt;/p&gt;

&lt;p&gt;Finally, we need to account for a situation where we are fed a path where something does not exist. This requires a simple if statement. Because the JSON data is treated as a dictionary, we can use the &lt;code&gt;get&lt;/code&gt; function to see if the key exists. It it does not, we simply break the loop and return the statement “Key does not exist.”&lt;/p&gt;

&lt;p&gt;In total, our function looks like this. Not the prettiest, but functional:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import re
import json 

def get_json_value_by_path(path, obj):
  json_dump = json.dumps(json_obj)
  data = json.loads(json_dump)
  paths = path.split('.')
  for i in range(1, len(paths)):
    res = re.findall(r'\d+', paths[i])
    if len(res) &amp;gt; 0:
      key = paths[i].split('[')[0]
      if not data.get(str(key)):
        return "Key does not exist"
      data = data[str(key)]
      for i in range(len(res)):
        idx = int(res[i])
        data = data[idx]
    else: 
      if not data.get(str(paths[i])):
        return "Key does not exist"
      data = data[str(paths[i])]
  print(data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>python</category>
      <category>json</category>
      <category>interview</category>
    </item>
    <item>
      <title>Changing Your AWS Default Profile</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Mon, 09 Nov 2020 14:20:04 +0000</pubDate>
      <link>https://forem.com/aohibbard/changing-your-aws-default-profile-2pa4</link>
      <guid>https://forem.com/aohibbard/changing-your-aws-default-profile-2pa4</guid>
      <description>&lt;p&gt;As I've been working with AWS recently, I find myself struggling to do really simple things. Newbie errors. I &lt;a href="https://dev.to/aohibbard/connecting-to-aws-amplify-3gi"&gt;recently documented my struggles&lt;/a&gt; with configuring an Amplify backend and wanted to return to the subject to reveal another issue that I had: changing the default profile.&lt;/p&gt;

&lt;p&gt;Before beginning, I wanted to say a bit about what Amplify is. According to &lt;a href="https://aws.amazon.com/amplify/"&gt;AWS's description&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;AWS Amplify is a set of products and tools that enables mobile and front-end web developers to build and deploy secure, scalable full stack applications, powered by AWS. With Amplify, you can configure app backends in minutes, connect them to your app in just a few lines of code, and deploy static web apps in three steps.&lt;br&gt;
In short, Amplify is a quick way to set up a backend. I'm using it in a shared project to run the backend of a React application.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now my struggle: I was running a shell script in the application to create an account in the backend of the web application, and the script required that I call on my AWS profile alias. When you configure an AWS account the first time, the profile name will default to "default." For some reason, the script did not like the name 'default', even when assigned to an environment variable. &lt;/p&gt;

&lt;p&gt;AWS does not have the clearest documentation for how to change the name of a profile, but it turns out to be pretty easy. If you have configured your settings correctly, you should have two local files that contain your account settings such as API key: &lt;code&gt;~/.aws/config&lt;/code&gt; and &lt;code&gt;~/.aws/credentials&lt;/code&gt;. If you're in an editor like VS Code, these might not be visible so just run &lt;code&gt;open&lt;/code&gt; before the path and you'll get something like a .rtf with your AWS configuration. You'll notice that in both files, account settings are listed and they having a header set in brackets, which contains the profile name. For the profile named default, simply delete the word default and assign the name you want. It must match in the two files. Save the two files. And that's it.&lt;/p&gt;

&lt;p&gt;If you want to preserve this account as the default one, just remember the alias you have given the profile run the command &lt;code&gt;export AWS_PROFILE=&amp;lt;my_profile&amp;gt;&lt;/code&gt; (with  acting as the name of your profile). You can perform this step whenever you want to change the default AWS profile. And that it. Three simple steps to change the name of your AWS default profile. &lt;/p&gt;

</description>
      <category>aws</category>
    </item>
    <item>
      <title>Setting Up a Basic Unit Test with RSpec</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Tue, 03 Nov 2020 16:27:54 +0000</pubDate>
      <link>https://forem.com/aohibbard/getting-started-with-rspec-12mg</link>
      <guid>https://forem.com/aohibbard/getting-started-with-rspec-12mg</guid>
      <description>&lt;p&gt;I have not spent a lot of time writing code in Ruby recently, but this weekend had the opportunity to develop a very simple trivia application in vanilla Ruby: two classes, a few dependencies, not much else. While this was easy enough, I wanted to add some tests to one of my classes, and I need a refresher. This post details my reintroduction to RSpec.&lt;/p&gt;

&lt;p&gt;As background, the application took a JSON file that contained many questions, each an object with three keys: a question (value: a string), an answer (value: a string), and incorrect (value: an array of strings). I wrote a Clue class (not the most descriptive name given it includes answers, but so it goes sometimes) with one function to parse the JSON file. This looked like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Clue

    attr_accessor :question, :answer, :wrong_answers, :all_answers
    @@all = [] #an array of all the clues

    def initialize()
        @@all &amp;lt;&amp;lt; self
    end

    def self.all 
        @@all
    end 

    def self.get_trivia
        json = JSON.parse(File.read("file_name.json"))
        json.each do |res| 
            clue = Clue.new 
            clue.question = res['question']
            clue.answer = res['correct']
            clue.wrong_answers = res['incorrect']
            clue.all_answers = [res['correct']].concat(res['incorrect'])
        end
    end 

end 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Having once upon a not-so-distant time spent a lot of time interacting with RSpect unit tests, I decided to use RSpec rather than Ruby'y standard library &lt;a href="https://en.wikibooks.org/wiki/Ruby_Programming/Unit_testing"&gt;&lt;code&gt;test-unit&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To get started with RSpec, you need to ensure that you have included the &lt;code&gt;gem 'rspec'&lt;/code&gt; in your Gemfile and have that installed correctly, then in your command line from the root direct run &lt;code&gt;rspec --init&lt;/code&gt;. This will create a directory 'spec' with the file 'spec-helper.br' as well as a root file '.rspec'. &lt;/p&gt;

&lt;p&gt;I next created a file under spec called 'clue_test.rb' which is where all of the work happens. It's easy to forget, but you need to remember to import the class you are working with in the test file, in this case: &lt;code&gt;require 'clue'&lt;/code&gt;. The next step was to test the different attributes of the Clue class. With testing, it is best to make the tests small and simple (an easy thing to do in a simple application). &lt;/p&gt;

&lt;p&gt;To start, I wanted to create a test &lt;code&gt;Clue&lt;/code&gt; object that would be the basis for the tests. RSpec relies on the verb &lt;code&gt;describe&lt;/code&gt; for a lot of its tests, and as my tests were describing the clue class, that's what we began with: &lt;code&gt;describe Clue do&lt;/code&gt;. Before any tests run, a new clue was created, fed with data from a Hash. There could be other ways of doing this, but I liked simulating the logic of the JSON parsing function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require 'clue'

describe Clue do 
    before do 
        new_clue = Hash["question" =&amp;gt; "How many folds does a chef's hat have?", "answer" =&amp;gt; 100, "wrong_answers" =&amp;gt; [90, 115, 50]]
        @first_clue = Clue.new
        @first_clue.question = new_clue['question']
        @first_clue.answer = new_clue['answer'] 
        @first_clue.wrong_answers = new_clue['wrong_answers']
        @first_clue.all_answers = [new_clue['answer']].concat(new_clue['wrong_answers'])
    end 

end 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The next step was to write a test. Go one by one. I wanted to start with some very simple. RSpec works by outlining a condition and then describing how the condition should behave. Tests generally look like something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;describe "thing" do 
   it "behaves like this" do 
       expect(variable).to eq(other thing)
    end
end 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the first test, I wanted to simply check if the &lt;code&gt;wrong_answers&lt;/code&gt; attribute of the newly instantiated Clue was an array. This looked:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    describe "wrong answers" do 
        it "includes an array of wrong answers" do 
            expect(@first_clue.wrong_answers.class).to eq(Array)
        end 
    end 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the initial writing of my tests, I had actually passed the wrong_answers to the Clue as a hash. It's a small but significant error, and one that really helps you to get to know your code much better, regardless of how simple you think it. &lt;/p&gt;

&lt;p&gt;There are a whole host of things you can beyond checking equivalence in RSpec. One simple test I wrote checked if the &lt;code&gt;.all_answers&lt;/code&gt; attribute include something from the &lt;code&gt;.wrong_answers&lt;/code&gt; array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    describe "all answers" do 
        it "includes wrong answers" do 
            expect(@first_clue.all_answers).to include(@first_clue.wrong_answers[0])
        end 
    end 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the end, I wrote a very simple test suite, but one that got me much closer to my code. I encourage you to check out the &lt;a href="https://github.com/rspec/rspec-core/blob/main/README.md"&gt;documentation&lt;/a&gt; and always test your code. &lt;/p&gt;

</description>
      <category>ruby</category>
      <category>rspec</category>
    </item>
    <item>
      <title>Anagram Checker</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Fri, 30 Oct 2020 21:10:39 +0000</pubDate>
      <link>https://forem.com/aohibbard/anagram-checker-58i3</link>
      <guid>https://forem.com/aohibbard/anagram-checker-58i3</guid>
      <description>&lt;p&gt;I was recently tasked in a technical interview to implement a function that iterated through an array of strings and checked if each string was an anagram of a string before it, returning an alphabetically sorted array of the results. The caveat was that certain features such as &lt;code&gt;reverse()&lt;/code&gt; were not allowed.&lt;/p&gt;

&lt;p&gt;So given the array &lt;code&gt;[‘drag’, ‘grad’, ‘’dad’, ‘banana’, ‘flimsy’, ‘add’]&lt;/code&gt; the function would output &lt;code&gt;['banana', 'dad', ‘drag’, ‘flimsy’]&lt;/code&gt;. I.e. Because 'grad' is an anagram of 'drag', it is removed from the array. &lt;/p&gt;

&lt;p&gt;My first approach was to determine how to detect an anagram. Typically I would do the sort of &lt;code&gt;word1.split('').sort() === word2.split('').sort&lt;/code&gt;, but that was not allowed. Instead, I implemented a function that first checked that the lengths of the two strings. Assuming they were of equal length, the function iterated through one of the strings, comparing it to the other, breaking if there is a letter that does not match up.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function isAnagram(word1, word2){
    if (word1.length !== word2.length) return false;
    word1 = word1.toLowerCase().split('')
    word2 = word2.toLowerCase().split('')
    for(let lttr of word1){
        // if letter in word1 is in word2, remove it from word2
        // if we never encounter a letter not in word2, 
        if (!word2.includes(lttr)){
            return false;
            break;
        } else {
            word2.splice(word2.indexOf(lttr), 1)
        }
    }
    return true
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By splicing the word2 array, we ensure that the amount of letters is equal as well. &lt;/p&gt;

&lt;p&gt;This function is a great start, but it is not going to work with the sample array we've been fed. Instead, I will call on this function inside of another one.&lt;/p&gt;

&lt;p&gt;To begin, I wrote an if statement that examines the length of the array. We know that the the first string in the array will &lt;em&gt;always&lt;/em&gt; be returned, because there is no string prior to it for it to be an anagram of. So if the array is empty or only includes only 1 string, the function will not continue and just return the array.&lt;/p&gt;

&lt;p&gt;I chose to not modify the array in place and use the extra memory to create a solution array. By the logic explained above, we know that the first string will always be included in the solution, so the array is initialized with the first string in the array: &lt;code&gt;let solution = [text[0]]&lt;/code&gt;. I then iterate over the subsequent array, calling on the &lt;code&gt;isAnagram&lt;/code&gt; function to check if the subsequent strings are anagrams of any of the strings in the solution array. Note that the for loop starts with i = 1, not 0, because we have already checked &lt;code&gt;text[0]&lt;/code&gt;. To do this, I filtered the solutions array against the current word in the for loop. If the word at &lt;code&gt;text[i]&lt;/code&gt; is not an anagram, it is pushed into the solution array. (An alternate way of doing this would be to modify the array in place, checking isAnagram() only for words that have an index less than i.)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function arrayAnagramChecker(text) {
    if (text.length &amp;lt;= 1) return text;
    let solution = [text[0]]
    for(let i = 1; i &amp;lt; text.length; i++){
        if (!solution.filter(word =&amp;gt; isAnagram(word, text[i])).length){
            solution.push(text[i])
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This covers most of the work, but remember that the the results have to be returned in a sorted array, not in their original order. Again, normally I would just do a &lt;code&gt;.sort&lt;/code&gt; or the slightly more laborious &lt;code&gt;.sort((a, b) =&amp;gt; a - b)&lt;/code&gt;. This was not enabled so I to implemented a slightly more elaborate sort:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    solution.sort(function(a, b){
            if(a &amp;lt; b) { return -1; }
            if(a &amp;gt; b) { return 1; }
            return 0;
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, our function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function funWithAnagrams(text) {
    if (text.length &amp;lt;= 1) return text;
    let solution = [text[0]]
    for(let i = 1; i &amp;lt; text.length; i++){
        if (solution.filter(word =&amp;gt; isAnagram(word, text[i])).length === 0){
            solution.push(text[i])
        }
    }
    solution.sort(function(a, b){
            if(a &amp;lt; b) { return -1; }
            if(a &amp;gt; b) { return 1; }
            return 0;
    })
    return solution
}

function isAnagram(word1, word2){
    if (word1.length !== word2.length) return false;
    word1 = word1.toLowerCase().split('')
    word2 = word2.toLowerCase().split('')
    for(let lttr of word1){
        // if letter in word1 is in word2, remove it from word2
        // if we never encounter a letter not in word2, 
        if (!word2.includes(lttr)){
            return false;
            break;
        } else {
            word2.splice(word2.indexOf(lttr), 1)
        }
    }
    return true
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And, just for kicks, I rewrote the function in Python, although I utilized &lt;code&gt;.sort&lt;/code&gt; there and also the &lt;code&gt;.sorted()&lt;/code&gt; function in a lambda to avoid create a separate function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def funWithAnagrams(text):
    if len(text) &amp;lt;= 1:
        return text
    solution = [text[0]]
    i = 1
    for i in range(len(text)):
        # if current word is not an anagram of list of solutions, add to solutions list
        anagrams = list(filter(lambda x : sorted(x) == sorted(text[i]), solution))
        if not anagrams:
            solution.append(text[i])
    solution.sort()
    return solution
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Connecting to AWS Amplify </title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Sat, 24 Oct 2020 13:26:39 +0000</pubDate>
      <link>https://forem.com/aohibbard/connecting-to-aws-amplify-3gi</link>
      <guid>https://forem.com/aohibbard/connecting-to-aws-amplify-3gi</guid>
      <description>&lt;p&gt;This week, I spent a lot of time trying to connect to databases. Or rather, I wasted a lot of time trying to connect to databases. An AWS Amplify application caused me quite a headache, so I wanted to provide a simple walkthrough to help troubleshoot some of the issues I was facing.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--PBLTEaKd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://jeffcrume.files.wordpress.com/2015/04/bang-head-against-brick-wall.jpg%3Fw%3D825%26h%3D550" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--PBLTEaKd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://jeffcrume.files.wordpress.com/2015/04/bang-head-against-brick-wall.jpg%3Fw%3D825%26h%3D550" alt="Image of a brick wall with a circle in the middle and an arrow pointing to the circle that reads 'Bang Head Here'"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Prerequisites
&lt;/h3&gt;

&lt;p&gt;To start, there are three packages that you will need get get things going: 1. &lt;a href="https://www.npmjs.com/package/@aws-amplify/cli"&gt;@aws-amplify-cli&lt;/a&gt;; 2. &lt;a href="https://www.npmjs.com/package/aws-amplify"&gt;@aws-amplify&lt;/a&gt;; 3. the most recent version of &lt;a href="https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html"&gt;AWS CLI&lt;/a&gt;. You will also need an AWS account. &lt;/p&gt;

&lt;h3&gt;
  
  
  Getting Going
&lt;/h3&gt;

&lt;p&gt;I was working with an existing Github repo, so I cloned that repo to my local machine and accessed a working branch. To configure access to the AWS resources, you will need to run &lt;code&gt;amplify configure&lt;/code&gt;. This command requires you to log into your AWS account and configure the access permissions through an IAM account. When going through these steps, you will be prompted to set a region. &lt;strong&gt;It is essential that the AWS region you choose matches the region configured in the application.&lt;/strong&gt; You can find this information in the repo's &lt;code&gt;team-provider-info.json&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You will also have to enter credentials for the IAM account that are produced in the AWS management console. These include an access key and a secret key. Take note of these in a secure location, though you can always produce a new one in the event that you lose it.&lt;/p&gt;

&lt;p&gt;In theory, everything should be working from here and you can just run &lt;code&gt;amplify init&lt;/code&gt; to connect things. When I ran amplify init, I hit the following error.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Initializing your environment: dev(node:22264) UnhandledPromiseRejectionWarning: InvalidAccessKeyId: The AWS Access Key Id you provided does not exist in our records.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This is one of those programming things where you want to beat your head against a wall. I &lt;em&gt;just&lt;/em&gt; told you the access key, why do you have to lose it? I tried going through the &lt;code&gt;amplify configure&lt;/code&gt; steps again, to no avail.&lt;/p&gt;

&lt;p&gt;(An aside on &lt;code&gt;amplify configure&lt;/code&gt;. The &lt;code&gt;amplify configure&lt;/code&gt; command menu creates the impression you are always adding a new user, when in fact it is a way of updating a user (see this &lt;a href="https://github.com/aws-amplify/amplify-cli/issues/4744"&gt;pull request&lt;/a&gt; for a more thorough discussion.)&lt;/p&gt;

&lt;p&gt;In the prerequisites, I mentioned installing the AWS CLI tools. This allowed me to diagnosis and fix the problem. If you run &lt;code&gt;aws configure&lt;/code&gt;, it will show you the last 4 characters of both the saved access key ID and secret access key, as well as the selected region. If any of this looks different from what you input &lt;code&gt;aws configure&lt;/code&gt;, this is the place to change it. I updated the values here, and voila. I ran &lt;code&gt;amplify init&lt;/code&gt;, and things were working. &lt;/p&gt;

&lt;h3&gt;
  
  
  TL;DR
&lt;/h3&gt;

&lt;p&gt;In summary, ensure you have the prerequisites. Run &lt;code&gt;amplify configure&lt;/code&gt;, then &lt;code&gt;amplify init&lt;/code&gt; and then run your app. Run &lt;code&gt;aws configure&lt;/code&gt; if things are not going right and then check your credentials. &lt;/p&gt;

</description>
      <category>aws</category>
      <category>amplify</category>
    </item>
    <item>
      <title>Getting Into TypeScript: What is a Dynamically Typed Language?</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Fri, 16 Oct 2020 14:06:56 +0000</pubDate>
      <link>https://forem.com/aohibbard/getting-into-typescript-what-is-a-dynamically-typed-language-33f5</link>
      <guid>https://forem.com/aohibbard/getting-into-typescript-what-is-a-dynamically-typed-language-33f5</guid>
      <description>&lt;p&gt;Take a look at job postings out there, and you'll see a lot of mentions of TypeScript. It doesn't take long to glean that TypeScript exists in relation to JavaScript, but what exactly is that relation?&lt;/p&gt;

&lt;p&gt;TypeScript was developed at Microsoft and first released in 2012. TypeScript is sort of a superset of JavaScript, adding a &lt;a href="https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html"&gt;type system&lt;/a&gt; on top of JavaScript. This description from the &lt;a href="https://github.com/microsoft/TypeScript"&gt;TypeScript Github repository&lt;/a&gt; is not a bad starting point:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;TypeScript is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To get at the core difference, it is important to understand what a dynamically typed language is, and what a statically typed language is. Dynamically typed languages include Perl, Ruby, Python, PHP, JavaScript—big languages in full-stack web development and the core languages we see being taught in bootcamps. Statically typed languages include  C, C++, Java, Rust, Go, Scala. &lt;/p&gt;

&lt;p&gt;Statically typed languages either work through type inference or force you to declare the type of a variable (e.g. string, integer) in writing the code so it is known at compilation. Dynamically typed languages do not require this. &lt;a href="https://docs.oracle.com/cd/E57471_01/bigData.100/extensions_bdd/src/cext_transform_typing.html"&gt;Oracle identifies two key differences&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;First, dynamically-typed languages perform type checking at runtime, while statically typed languages perform type checking at compile time. This means that scripts written in dynamically-typed languages...can compile even if they contain errors that will prevent the script from running properly (if at all). If a script written in a statically-typed language (such as Java) contains errors, it will fail to compile until the errors have been fixed.&lt;/p&gt;

&lt;p&gt;Second, statically-typed languages require you to declare the data types of your variables before you use them, while dynamically-typed languages do not. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Dynamically typed languages offer a bit more speed for the coder, sparing you the step of type declaration. As mentioned above, your code will compile without errors in a dynamically typed language. It's the sort of logic that allows us to do get something like &lt;code&gt;"1" + 1 = "11"&lt;/code&gt; or &lt;code&gt;"alert" + [1,2] = "alert1,2"&lt;/code&gt;in JavaScript. Although we can sometimes use this to our advantage, it can also result in errors. &lt;/p&gt;

&lt;p&gt;TypeScript then sits on top of JavaScript and allows a bit more control over things. Consider this example from the &lt;a href="https://www.typescriptlang.org/docs/handbook/typescript-tooling-in-5-minutes.html"&gt;TypeScript documentation&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function greeter(person: string) {
  return "Hello, " + person;
}

let user = [0, 1, 2];

document.body.textContent = greeter(user);
Argument of type 'number[]' is not assignable to parameter of type 'string'.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What we see is by declaring the type of the person argument, anything passed in that is not a string will yield an error. It's a small addition but a huge amount of control added to your programming. &lt;/p&gt;

&lt;p&gt;I'm a big fan of knowing the history of things, and this video of &lt;a href="https://channel9.msdn.com/Events/Visual-Studio/Launch-2013/WC109"&gt;Jonathan Turner talking about TypeScript in 2013&lt;/a&gt; is a great resource and starting place. &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>typescript</category>
    </item>
    <item>
      <title>Counting Array of Arrays</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Fri, 09 Oct 2020 15:55:51 +0000</pubDate>
      <link>https://forem.com/aohibbard/counting-array-of-arrays-2j8l</link>
      <guid>https://forem.com/aohibbard/counting-array-of-arrays-2j8l</guid>
      <description>&lt;p&gt;A few weeks ago in a technical interview, I was given a challenge that involved iterating through an arrays. I do not have the exact wording, but it was something akin, to given a family tree in the format of an array of arrays, return all the nodes with only one parent or no parents. To visualize the data, I was shown this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1   2    4 
 \ /   / | \
  3   5  8  9
   \ / \     \
    6   7     11
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;From this data display, we can deduce the nodes with only one parent are [5, 7, 8, 9, 11] and the nodes with no parent are [1, 2, 4]. While looking at the data in this format cause me to think "TREE!", this was not the case as this information was given as an array of arrays, with each sub-array including two values, the index at 0 referring to the parent and at index 1 referring to the child. Practically, this looked like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const parentChildPairs = [
    [1, 3], [2, 3], [3, 6], [5, 6],
    [5, 7], [4, 5], [4, 8], [4, 9], [9, 11]
  ];
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I came up with, what I think is, a rather solid linear run-time solution. This involved creating two objects, one to count the number of times parents appear and the other to count the number of times that children appear: &lt;code&gt;let parentsObj = {}&lt;/code&gt; and &lt;code&gt;let childObj = {}&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;The next step was to iterate over the entire collection and count where numbers appear. If a number appears in a sub-array at index 0, it should be counted as a parent; if it appears in a sub-array at index 1, it should be counted in the child object. Practically, this looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  function findNodesWithZeroAndOneParents(arr){
    let parentsObj = {}
    let childObj = {}
    for (const subArr of arr){
      //count parents
      if (!parentsObj[subArr[0]]){
        parentsObj[subArr[0]] = 1
      } else {
        parentsObj[subArr[0]] += 1
      }
      //count children
      if (!childObj[subArr[1]]){
        childObj[subArr[1]] = 1
      } else {
        childObj[subArr[1]] += 1
      }
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The next step is to go through each collection and take out the data that we need: children who have no parents, and children who have only one parent. In both cases, it is extremely helpful to use JavaScript's &lt;code&gt;[Object.keys() method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)&lt;/code&gt;, yielding an array of the object keys that can be filtered to get the results that we need. &lt;/p&gt;

&lt;p&gt;To find the individuals with no parent, we need to compare the individuals in our &lt;code&gt;parentsObj&lt;/code&gt; with those in the &lt;code&gt;childObj&lt;/code&gt;. Any key that appears in the &lt;code&gt;parentsObj&lt;/code&gt; but no the &lt;code&gt;childObj&lt;/code&gt; would be included in the array of individuals with no parent. I chose to do this by finding the keys of the &lt;code&gt;parentObj&lt;/code&gt; and then filtering those in relation to the keys of the &lt;code&gt;childObj&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Object.keys(parentsObj).filter(key =&amp;gt; !Object.keys(childObj).includes(key))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;To find children with only parent requires another Object.keys method but a slightly easier: take all of the keys from the &lt;code&gt;childObj&lt;/code&gt; and filter them, finding any key whose value is equal to one (that is, any child who only appears one time at sub-array index one).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Object.keys(childObj).filter(key =&amp;gt; childObj[key] === 1)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Once we account for an edge case in which the array fed into the function is empty, we have an answer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  function findNodesWithZeroAndOneParents(arr){
    if (arr.length === 0) return 0;
    let parentsObj = {}
    let childObj = {}
    for (const subArr of arr){
      if (!parentsObj[subArr[0]]){
        parentsObj[subArr[0]] = 1
      } else {
        parentsObj[subArr[0]] += 1
      }
      if (!childObj[subArr[1]]){
        childObj[subArr[1]] = 1
      } else {
        childObj[subArr[1]] += 1
      }
    }
    let noParents = Object.keys(parentsObj).filter(key =&amp;gt; !Object.keys(childObj).includes(key))
    let oneParent = Object.keys(childObj).filter(key =&amp;gt; childObj[key] === 1)
    return {"No Parents": noParents, "One Parent": oneParent}
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;NB: Because JavaScript does not allow return on multiple variables, I returned the answer as an object, with the keys referring to the different information needed and their values referring to the appropriate arrays.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>technicalinterviews</category>
    </item>
    <item>
      <title>What exactly is JSON?</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Fri, 02 Oct 2020 14:15:48 +0000</pubDate>
      <link>https://forem.com/aohibbard/what-exactly-is-json-3nd6</link>
      <guid>https://forem.com/aohibbard/what-exactly-is-json-3nd6</guid>
      <description>&lt;p&gt;During a recent interview, I was tasked with working with a JSON object in the language of my choice. While I'll skip over the the particularities of the situation, I realized that I had some uncertainty over what exactly JSON is. I've worked with JSON extensively in JavaScript concepts, and I've utilized methods like &lt;code&gt;JSON.parse()&lt;/code&gt; and &lt;code&gt;JSON.stringify()&lt;/code&gt;, knowing that these are valuable in managing the data and sending it between the front and back end. But there was a conceptual foundation missing from my practical usage. Let's start with a an official definition from &lt;a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON"&gt;Mozilla&lt;/a&gt;: &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If we start with just the name, it is the second half that really stands out. JSON is an object notation, or as Mozilla says, a "text-based format" for representing data. This of course makes sense. If we are utilizing a back-end such as Rails or Django, it does not make much sense that our data would be circulating as a JavaScript object. &lt;/p&gt;

&lt;p&gt;So JSON is in fact a text-based notation (think XML, YAML) that format data into a readable object format for JavaScript. This is why it is import to run &lt;code&gt;JSON.parse()&lt;/code&gt; when data enters the a JavaScript front end: because it is coming through as a string, albeit one that is formatted as a JavaScript object. If we were just sending a really long string this would be, well, a pain. But of course.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/FaLhiZQHrBIYw/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/FaLhiZQHrBIYw/giphy.gif" alt='Alan Rickman as Severus Snape in a gloomy dungeon saying mouth "Obviously." "Obviously" is the caption in the image.'&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Conventional wisdom suggests that, with the rise of JavaScript, JSON took the throne from XML as a preferred way to send data in APIs given its easier readability and accessibility as a JavaScript object. Indeed, working with JSON is just as easy as working with JavaScript objects because (if parsed), JSON is an JavaScript object. Most histories date JSON back to 1999 or 2000 and it began to pick up usage in the aughts, but really grew in the last decade particularly when it became an ECMA international standard in 2013. (For some context on JSON vs. XML, &lt;a href="https://www.guru99.com/json-vs-xml-difference.html"&gt;this post&lt;/a&gt; has a nice graph, with some highlights being that JSON is easier to read and parse, though has some more security vulnerability.)&lt;/p&gt;

&lt;p&gt;What about generating JSON outside of JavaScript? The standardization of JSON has made it very easy to work with and many languages have native support for working with JSON. In Python, you simply need to &lt;code&gt;import json&lt;/code&gt; and there are plenty of functions available to parse JSON data and to format data into JSON. There are also libraries like Jackson and GSON in Java. And frameworks have plenty of support too: Rails, for example, has the Active Model Serializer, although I'm a big fan of Fast_JSON API as it offers a faster performance. &lt;/p&gt;

&lt;p&gt;JSON is not a difficult concept to understand. But it is always a good reminder to think through the basic concepts of what you are working with. &lt;/p&gt;

</description>
      <category>json</category>
      <category>javascript</category>
    </item>
    <item>
      <title>JavaScript: Map &amp; Set</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Fri, 25 Sep 2020 15:18:05 +0000</pubDate>
      <link>https://forem.com/aohibbard/javascript-map-set-2d0e</link>
      <guid>https://forem.com/aohibbard/javascript-map-set-2d0e</guid>
      <description>&lt;p&gt;While hunting for my first job as a software engineer, I have spent a LOT of time on LeetCode and HackerRank. Everyone has a different strategy for how they approach this studying. At some point after I’ve solved a problem, I like to look at how other individuals have approached the same situation. And from doing this, I’ve picked up two very valuable assets in JavaScript: map and set.&lt;/p&gt;

&lt;h2&gt;
  
  
  SET
&lt;/h2&gt;

&lt;p&gt;I find myself using Set all the time. It is an exceptional tool for removing duplicates in an array. Imagine you have &lt;code&gt;let arr = [1, 2, 3, 4, 1]&lt;/code&gt;. Run &lt;code&gt;[...new Set(arr)]&lt;/code&gt;, and you will get [1, 2, 3, 4]. Great! But I know this is a limited use of Set so I wanted to dig a bit deeper.&lt;/p&gt;

&lt;p&gt;What is Set? If we take a set like the one above and run &lt;code&gt;typeof()&lt;/code&gt; on it, we see that a set is a type of object in JavaScript. It is worth remembering there are &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures"&gt;two structural types&lt;/a&gt; in JavaScript: objects and functions. Within the object family tree, we find arrays, maps, sets as well as WeakSets and WeakMaps. &lt;/p&gt;

&lt;p&gt;So Set is a type of object. As &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"&gt;Mozilla describes&lt;/a&gt;: “Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.” They key to set is the condition of uniqueness. &lt;/p&gt;

&lt;p&gt;It is also worth noting that Set allows us to iterate over it. So we can call &lt;code&gt;forEach&lt;/code&gt; on a Set. Several other methods also allow iteration: &lt;code&gt;Set.prototype.keys()&lt;/code&gt; and &lt;code&gt;Set.prototype.values()&lt;/code&gt; create iterator objects that return the keys or values of the set. If we had something like &lt;code&gt;let mySet = new Set([1, 2, 3, 4, 4, 4])&lt;/code&gt;, mySet would be of size 4 and would equal &lt;code&gt;{1, 2, 3, 4}&lt;/code&gt;. What is important to note about this is that if we wanted to to find the values or keys of this set, the result would look the same, because in this case, the values and keys are effectively the same. Set store objects and arrays inside of it as well, creating nesting. If we wanted to add &lt;code&gt;let arr = [1, 2, 3, 4, 4]&lt;/code&gt; to mySet by performing &lt;code&gt;mySet.add(arr)&lt;/code&gt;, mySet would take on size five and look like &lt;code&gt;{1, 2, 3, 4, arr: [1, 2, 3, 4, 4]}&lt;/code&gt;. It is noteworthy here that set allows non-unique values inside the this array because it is not looking inside the value stored. &lt;/p&gt;

&lt;h2&gt;
  
  
  MAP
&lt;/h2&gt;

&lt;p&gt;Map turns out to be quite similar, but does not uphold the uniqueness factor. Like set, a Map does not use or contain keys by default, but if keys are added, the can be any value (e.g. primitive data types, functions, objects). Similarly, Map allows out to iterate over, and values are placed in the sequence in which they are added (or &lt;code&gt;set&lt;/code&gt;). There’s a &lt;a href="https://stackoverflow.com/questions/18541940/map-vs-object-in-javascript#:~:text=According%20to%20mozilla%3A-,A%20Map%20object%20can%20iterate%20its%20elements%20in%20insertion%20order,%2C%20value%5D%20for%20each%20iteration.&amp;amp;text=Objects%20are%20similar%20to%20Maps,is%20stored%20at%20a%20key."&gt;StackOverflow post&lt;/a&gt; containing an older explanation of the differences between objects and Maps that is helpful. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this, Objects have been used as Maps historically; however, there are important differences between Objects and Maps that make using a Map better.&lt;br&gt;
An Object has a prototype, so there are default keys in the map. However, this can be bypassed using map = Object.create(null). The keys of an Object are Strings, where they can be any value for a Map. You can get the size of a Map easily while you have to manually keep track of size for an Object.&lt;br&gt;
Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.&lt;br&gt;
Use objects when there is logic that operates on individual elements.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;With both Map and Set, there are a lot of properties and methods &lt;br&gt;
Tania Rascia has a &lt;a href="https://www.taniarascia.com/understanding-map-and-set-javascript/"&gt;great post&lt;/a&gt; outlining some of these, but essential ones are set, delete, get, has, clear, and size for Map. All considered, Set and Map are essential tools in modern JavaScript.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JS String Encryption Algorithm</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Tue, 15 Sep 2020 11:12:44 +0000</pubDate>
      <link>https://forem.com/aohibbard/js-string-encryption-algorithm-1m63</link>
      <guid>https://forem.com/aohibbard/js-string-encryption-algorithm-1m63</guid>
      <description>&lt;p&gt;This week, I was given a technical challenge that involved creating an encryption for a string. I’m pulling from memory, but the the task was roughly as follows: given a string, an r value, and a c value, encrypt the string so that it is split into a grid measuring r characters across and c characters down. Then, transform the string so that it reads top to bottom. The string will always be a length measuring r * c, and spaces count toward the string.&lt;/p&gt;

&lt;p&gt;I was given a few test cases for this algorithm, which I’ve lost, but I’ve created my own for the purposes of this demo. Let’s work with the very convenient (and broken) string I gave myself: "This message is 25 charac" and r and c values both equal to 5.&lt;/p&gt;

&lt;p&gt;According to the instructions, we would want to transform this string to look something like:&lt;/p&gt;

&lt;p&gt;“This &lt;br&gt;
messa&lt;br&gt;
ge is&lt;br&gt;
 25 c&lt;br&gt;
harac”&lt;/p&gt;

&lt;p&gt;This should then give us the following string:&lt;/p&gt;

&lt;p&gt;"Tmg hhee2ais 5rssi a ascc"&lt;/p&gt;

&lt;p&gt;My approach to this was sound, but the final code was clumsy. So I want to walk you through how I approached it and then refactored it.&lt;/p&gt;

&lt;p&gt;Following the instructions, I thought the best approach was to manipulate the string into a matrix measuring r rows and c columns, and the transform that matrix into a string, moving down column by column. &lt;/p&gt;

&lt;p&gt;My first steps were to make a function with three arguments (duh) &lt;code&gt;function encrypString(message, r, c)&lt;/code&gt; declare a matrix &lt;code&gt;let matrix = []&lt;/code&gt; and then to split the string into an array &lt;code&gt;let msgArr = message.split(‘’)&lt;/code&gt;. Easy enough&lt;/p&gt;

&lt;p&gt;The next step was to populate the array. To do this, I opted for the creation of a for loop inside a while loop. With each iteration of the for loop, a new character was added to an empty array, which would stop when the array achieves a length of &lt;code&gt;c - 1&lt;/code&gt; — that is, the end column of the matrix given by the function (in this case 5). When the for loops completes, this new subarray is pushed into the matrix. This loop operates destructively on the msgArr variable, running until the array is empty.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  while(msgArr.length &amp;gt; 0){
    let newArr = [];
    for(let i = 0; i &amp;lt; c; i++){
      let newChar = msgArr.splice(0, 1)
      newArr.push(newChar)
    }
    matrix.push(newArr.flat())
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Admittedly, this is not the most beautiful solution. We’ll come back to a better alternative later that is less clunky. But for the time being, this produces the matrix that we need.&lt;/p&gt;

&lt;p&gt;In my handling, the next step was to create an empty string which will be used to produced a return value (our answer) (&lt;code&gt;let str = ‘’&lt;/code&gt;)and then manipulate the array by columns so that we can have our encrypted string. I chose the very clunky way of running a for loop inside of a for loop, once again manipulating the string one character at a time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for (let i = 0; i &amp;lt; c; i++){
    for (let j = 0; j &amp;lt; r; j++){
      str += matrix[j][i]
    }
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I’ll note the importance thing here is how the i and j values are set. The outer for loop runs according to the c value — that is the column — and the inner loop runs according to the row size (r). Every time the inner loop completes, this means we have emptied the nth column of every row, and then can move onto the next one. This does the work that we need it to and helps us arrive, but it’s not the most beautiful.&lt;/p&gt;

&lt;p&gt;Having completed this text, I knew I could do better. These loops take too much time. Let’s look first at our initial loop to create the matrix using a while loop inside a for loop.&lt;/p&gt;

&lt;p&gt;I realized two things going into this. First, I did not need to take up additional memory space by saving my original string under a new variable. I could simply declare message = message.split(‘’). Goodbye &lt;code&gt;msgArr&lt;/code&gt; variable. Second, I did not abandon a loop entirely, but I did find a way to form the matrix one row at a time rather than one character at time by employing splice (still destructively manipulating the array).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  for(let i = 0; i &amp;lt; c; i++){
      matrix.push(message.splice(0, c))
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;What is happening here is the message array is spliced each time from its beginning to c characters, destructively manipulating the message array and producing a new array of length c, which is then pushed to our matrix. Additionally, because splice produces an array, there is no need to declare an empty array with each loop. This allows the loop to run only c times, rather than once per character plus once per row (in our example 25 times for the string in the for loop, plus 5 times for the while loop. That would get long fast!).&lt;/p&gt;

&lt;p&gt;This is good progress. But we can do better still. Once again, we have a double for loop to manipulate our string. This is not necessary. A single loop can accomplish the same goal. Rather than manipulate the array one character at a time, we can go one column at a time using destructing and the map function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let encoded = []
while (matrix.length &amp;gt; 0){
    encoded.push(...matrix.map(subArr =&amp;gt; subArr.shift()))
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The restructuring allows us to pass in the matrix, and then map new arrays from each of its subarrays. By calling shift, we destructively manipulate the array, pulling the first value from each subarray. In total, this gives us an entire column of the matrix with each loop. What we achieved with two for loops that run character by character now run column by column. Not bad!&lt;/p&gt;

&lt;p&gt;I’ll note that instead of creating an empty string, I’ve chosen to push these subarrays to an empty array, which requires calling &lt;code&gt;.join(‘’)&lt;/code&gt; in our return value. I think &lt;code&gt;join&lt;/code&gt; could be called on the mapped arrays as well and we could just push to the string as we did originally, &lt;code&gt;str += ...&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;Let's compare, starting with our old version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function encryptString(message, r, c){
  let matrix = []
  let msgArr = message.split('')
  while(msgArr.length &amp;gt; 0){
    let newArr = [];
    for(let i = 0; i &amp;lt; c; i++){
      let newChar = msgArr.splice(0, 1)
      newArr.push(newChar)
    }
    matrix.push(newArr.flat())
  }
  message = message.split('')
  for(let i = 0; i &amp;lt; c; i++){
      let newArr = []
      newArr.push(message.splice(0, c))
      matrix.push(newArr)
  }
  let str = ''
  for (let i = 0; i &amp;lt; c; i++){
    for (let j = 0; j &amp;lt; r; j++){
      str += matrix[j][i]
    }
  }
  console.log(str)
  return str
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The new version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function encryptString(message, r, c){
  let matrix = []
  message = message.split('')
  for(let i = 0; i &amp;lt; c; i++){
      matrix.push(message.splice(0, c))
  }
  let word = []
  while(matrix[0].length &amp;gt; 0){
    word.push(...matrix.map(subArr =&amp;gt; subArr.shift()))
  }
  return word.join('')
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This drastically cuts down the length of the function and the run time, and I think ends up being a lot more readable too. Not bad! If only I could have done this in the live coding exercise. &lt;/p&gt;

&lt;p&gt;UPDATE 21 SEPTEMBER&lt;/p&gt;

&lt;p&gt;Always trying to improve, I've stayed looking at this algorithm and realized that, with a little pattern recognition, there would probably be a better way to perform the string encryption. And I realized that we can effectively disregard the c variable and simply collect the values row by row. Imagine r = 5. We know the string will be a multiple of 5, so we can just collect every fifth value to form the first part of the string. These would be the values of column[0]. We need to append the second part of the string (this would have been column[1]), which would be every string at index of r - 1. With the addition of a counter and a while loop, this logic becomes a lot easier to track.&lt;/p&gt;

&lt;p&gt;This logic could be kept inside a for loop, checking every index value or we can just implement this by filtering the string and checking if the index of the specific character divided by r has a remainder equal to the column it would be in. With x corresponding to the column number, this looks like: &lt;code&gt;message.indexOf(char) % r === x&lt;/code&gt;. You can see this all at work in a much more efficient function below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function encryptString(message, r, c){
  message = message.split('')
  let newStr = ''
  let x = 0
  while(x &amp;lt; r){
    // for every turn of the loop on x, add the character at the value r - x (x corresponding to the rows)
    newStr += message.filter(char =&amp;gt; message.indexOf(char) % r === x).join('')
    x++
  }
  return newStr
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Transactions in MongoDB</title>
      <dc:creator>aohibbard</dc:creator>
      <pubDate>Fri, 11 Sep 2020 16:39:59 +0000</pubDate>
      <link>https://forem.com/aohibbard/transactions-in-mongodb-545e</link>
      <guid>https://forem.com/aohibbard/transactions-in-mongodb-545e</guid>
      <description>&lt;p&gt;I’ve recently been building a web app with Node and Express and decided to go full MERN stack and integrate MongoDB—or more accurately, I’m working with mongoose, the object modeling tool for MongoDB. I’ve spent most of my time working with SQL databases (PostgreSQL especially) and there are a lot of great posts out in the world that chart the difference between SQL and NoSQL databases.&lt;/p&gt;

&lt;p&gt;One of the processes I had taken for granted in a SQL context is transactions. In the most basic context, a transaction involves the propagation of one or more changes to a database. Order matters in transactions. Consider an event where you have a value A, value B, and value C. Value A needs to deduct something from value B so that value C can deduct something from value A. Assume value A is 10, value B is 20, and value C is 100, and the value deducted is 15. If C deducts from A before A can deduct from B, that means A will have a negative value at some point. In this benign hypothetical, this is fine. But imagine we are dealing with a bank: A could incur overdraft penalties. In the real world, this could get sticky. If we were dealing with inventories in eCommerce, people could be buying things they thing are available but actually are not. Order matters!&lt;/p&gt;

&lt;p&gt;TutorialsPoint has a helpful breakdown of the properties of transactions, which can be remembered through the acronym &lt;a href="https://www.tutorialspoint.com/sql/sql-transactions.htm"&gt;ACID&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;• Atomicity − ensures that all operations within the work unit are &amp;gt; completed successfully. Otherwise, the transaction is aborted at &lt;br&gt;
the point of failure and all the previous operations are rolled   &amp;gt; back to their former state. &lt;br&gt;
• Consistency − ensures that the database properly changes states &lt;br&gt;
upon a successfully committed transaction. &lt;br&gt;
• Isolation − enables transactions to operate independently of and transparent to each other. &lt;br&gt;
• Durability − ensures that the result or effect of a committed &lt;br&gt;
transaction persists in case of a system failure. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Historically, ACID transactions were not a part of MongoDB. This had to do with the the way NoSQL databases were used, but their growing popularity changed that. See Laura Schaefer’s blog post from January 2019 &lt;a href="https://www.mongodb.com/blog/post/mongodb-qa-whats-the-deal-with-data-integrity-in-relational-databases-vs-mongodb"&gt;on the subject&lt;/a&gt;: &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;They explained how, for non-relational databases like MongoDB, &lt;br&gt;
multi-document ACID transactions have historically been a bit of &lt;br&gt;
an odd case. With a document data model, you naturally prefer to &lt;br&gt;
keep changes localized to the document you are working on, so the &lt;br&gt;
single operation ACID compliance was often enough.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;With MongoDB 4.0, it became possible to execute ACID transactions, but that did not mean it was impossible before. The package &lt;a href="https://www.npmjs.com/package/fawn"&gt;Fawn&lt;/a&gt; made it possible to execute ACID transactions in MongoDb. &lt;/p&gt;

&lt;p&gt;The development of ACID transactions in MongoDB was motivated, in part, by the long shadow relational databases with table models have cast over the history of databases. As Mat Keet and Alyson Cabral &lt;a href="https://www.mongodb.com/blog/post/mongodb-multi-document-acid-transactions-general-availability"&gt;wrote in June of this year&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;With subdocuments and arrays, documents allow related data to be &lt;br&gt;
modeled in a single, rich and natural data structure, rather than  &amp;gt; spread across separate, related tables composed of flat rows and  &amp;gt; columns. As a result, MongoDB’s existing single document atomicity  &amp;gt; guarantees can meet the data integrity needs of most applications.  &amp;gt; In fact, when leveraging the richness and power of the document  &amp;gt;  &amp;gt; model, we estimate 80%-90% of applications don’t need multi- document transactions at all.&lt;br&gt;
However, some developers and DBAs have been conditioned by 40 &lt;br&gt;
years of relational data modeling to assume multi-document &lt;br&gt;
transactions are a requirement for any database, irrespective of &lt;br&gt;
the data model they are built upon. Some are concerned that while &lt;br&gt;
multi-document transactions aren’t needed by their apps today, they  &amp;gt; might be in the future. And for some workloads, support for ACID  &amp;gt; transactions across multiple documents is required.&lt;br&gt;
As a result, the addition of multi-document transactions makes it  &amp;gt; easier than ever for developers to address a complete range of use  &amp;gt; cases on MongoDB. For some, simply knowing that they are available  &amp;gt; will assure them that they can evolve their application as needed,  &amp;gt; and the database will support them.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In Node, ACID transactions require the creation of helper functions that rely on async/await patterns in JavaScript to ensure that not only are transactions completely successfully but are completed in the correct order. For more on the topic, I recommend &lt;a href="https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions"&gt;this post on MongoDB's blog.&lt;/a&gt;&lt;/p&gt;

</description>
      <category>mongodb</category>
      <category>node</category>
      <category>nosql</category>
    </item>
  </channel>
</rss>
