<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mike Shannon</title>
	<atom:link href="https://mikeshannon.com/feed" rel="self" type="application/rss+xml" />
	<link>https://mikeshannon.com</link>
	<description>Developing Software and Products on the Web</description>
	<lastBuildDate>Tue, 20 Dec 2022 09:06:19 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.8</generator>
	<item>
		<title>Creating Images from text descriptions using DALL-E</title>
		<link>https://mikeshannon.com/creating-images-using-dall-e</link>
		
		<dc:creator><![CDATA[Mike Shannon]]></dc:creator>
		<pubDate>Tue, 20 Dec 2022 09:00:34 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<guid isPermaLink="false">https://mikeshannon.com/?p=630</guid>

					<description><![CDATA[This is one of the coolest things I&#8217;ve seen in a long time. I&#8217;m able to write a simple or even a complex text description and an AI / computer ...]]></description>
										<content:encoded><![CDATA[
<p>This is one of the coolest things I&#8217;ve seen in a long time.</p>



<p>I&#8217;m able to write a simple or even a complex text description and an AI / computer generates the images for me within a few seconds. There are a few of these AI-based image services out there. I&#8217;m currently trying out DALL-E.</p>



<h2>Here are a few photos I&#8217;ve generated recently</h2>



<p>Text prompts are in &#8220;quotes&#8221; followed by the image that DALL-E generated for me:</p>



<h3>“Cybertronic robot orange and white, LEDs, high detail, sharp, studio, digital art”</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1024" src="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.46.34-Cybertronic-robot-orange-and-white-LEDs-high-detail-sharp-studio-digital-art-1024x1024.png" alt="" class="wp-image-631" srcset="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.46.34-Cybertronic-robot-orange-and-white-LEDs-high-detail-sharp-studio-digital-art.png 1024w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.46.34-Cybertronic-robot-orange-and-white-LEDs-high-detail-sharp-studio-digital-art-300x300.png 300w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.46.34-Cybertronic-robot-orange-and-white-LEDs-high-detail-sharp-studio-digital-art-150x150.png 150w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.46.34-Cybertronic-robot-orange-and-white-LEDs-high-detail-sharp-studio-digital-art-768x768.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<h3>“Photograph of a spaceship rising out of the ocean. The sun is setting and and there is a large planet visible in the sky. Someone wearing a robe stands on a cliff looking at the spaceship.”</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1024" src="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.46.45-Photograph-of-a-spaceship-rising-out-of-the-ocean.-The-sun-is-setting-and-and-there-is-a-large-planet-visible-in-the-sky.-Someone-wearing-a-robe-stand-1024x1024.png" alt="" class="wp-image-632" srcset="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.46.45-Photograph-of-a-spaceship-rising-out-of-the-ocean.-The-sun-is-setting-and-and-there-is-a-large-planet-visible-in-the-sky.-Someone-wearing-a-robe-stand.png 1024w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.46.45-Photograph-of-a-spaceship-rising-out-of-the-ocean.-The-sun-is-setting-and-and-there-is-a-large-planet-visible-in-the-sky.-Someone-wearing-a-robe-stand-300x300.png 300w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.46.45-Photograph-of-a-spaceship-rising-out-of-the-ocean.-The-sun-is-setting-and-and-there-is-a-large-planet-visible-in-the-sky.-Someone-wearing-a-robe-stand-150x150.png 150w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.46.45-Photograph-of-a-spaceship-rising-out-of-the-ocean.-The-sun-is-setting-and-and-there-is-a-large-planet-visible-in-the-sky.-Someone-wearing-a-robe-stand-768x768.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<h3>“A white fur monster in a blue room”</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1024" src="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.47.13-A-white-fur-monster-in-a-blue-room-1024x1024.png" alt="" class="wp-image-634" srcset="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.47.13-A-white-fur-monster-in-a-blue-room.png 1024w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.47.13-A-white-fur-monster-in-a-blue-room-300x300.png 300w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.47.13-A-white-fur-monster-in-a-blue-room-150x150.png 150w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.47.13-A-white-fur-monster-in-a-blue-room-768x768.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<h3>“A Cybertronic robot full body on a mountain top overlooking a lake city, LEDs, high detail, sharp, studio, digital art, 8k”</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1024" src="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.47.48-A-Cybertronic-robot-full-body-on-a-mountain-top-overlooking-a-lake-city-LEDs-high-detail-sharp-studio-digital-art-8k-1024x1024.png" alt="" class="wp-image-638" srcset="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.47.48-A-Cybertronic-robot-full-body-on-a-mountain-top-overlooking-a-lake-city-LEDs-high-detail-sharp-studio-digital-art-8k.png 1024w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.47.48-A-Cybertronic-robot-full-body-on-a-mountain-top-overlooking-a-lake-city-LEDs-high-detail-sharp-studio-digital-art-8k-300x300.png 300w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.47.48-A-Cybertronic-robot-full-body-on-a-mountain-top-overlooking-a-lake-city-LEDs-high-detail-sharp-studio-digital-art-8k-150x150.png 150w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.47.48-A-Cybertronic-robot-full-body-on-a-mountain-top-overlooking-a-lake-city-LEDs-high-detail-sharp-studio-digital-art-8k-768x768.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<h3>“The solar system without words, digital art”</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1024" src="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.48.33-The-solar-system-without-words-digital-art-1024x1024.png" alt="" class="wp-image-640" srcset="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.48.33-The-solar-system-without-words-digital-art.png 1024w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.48.33-The-solar-system-without-words-digital-art-300x300.png 300w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.48.33-The-solar-system-without-words-digital-art-150x150.png 150w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.48.33-The-solar-system-without-words-digital-art-768x768.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<h3>“A portrait of a hamster in a library, Sigma 85 mm f/1.4.”</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1024" src="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.48.42-A-portrait-of-a-hamster-in-a-library-Sigma-85-mm-f_1.4.-1024x1024.png" alt="" class="wp-image-641" srcset="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.48.42-A-portrait-of-a-hamster-in-a-library-Sigma-85-mm-f_1.4..png 1024w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.48.42-A-portrait-of-a-hamster-in-a-library-Sigma-85-mm-f_1.4.-300x300.png 300w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.48.42-A-portrait-of-a-hamster-in-a-library-Sigma-85-mm-f_1.4.-150x150.png 150w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.48.42-A-portrait-of-a-hamster-in-a-library-Sigma-85-mm-f_1.4.-768x768.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<h3>“Photograph of a robot with red spikey hair on a mountain top overlooking a lake. There is a large planet system in the sky on the horizon.”</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1024" src="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.49.08-Photograph-of-a-robot-with-red-spikey-hair-on-a-mountain-top-overlooking-a-lake.-There-is-a-large-planet-system-in-the-sky-on-the-horizon.-1024x1024.png" alt="" class="wp-image-643" srcset="https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.49.08-Photograph-of-a-robot-with-red-spikey-hair-on-a-mountain-top-overlooking-a-lake.-There-is-a-large-planet-system-in-the-sky-on-the-horizon..png 1024w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.49.08-Photograph-of-a-robot-with-red-spikey-hair-on-a-mountain-top-overlooking-a-lake.-There-is-a-large-planet-system-in-the-sky-on-the-horizon.-300x300.png 300w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.49.08-Photograph-of-a-robot-with-red-spikey-hair-on-a-mountain-top-overlooking-a-lake.-There-is-a-large-planet-system-in-the-sky-on-the-horizon.-150x150.png 150w, https://mikeshannon.com/wp-content/uploads/2022/12/DALL·E-2022-12-20-00.49.08-Photograph-of-a-robot-with-red-spikey-hair-on-a-mountain-top-overlooking-a-lake.-There-is-a-large-planet-system-in-the-sky-on-the-horizon.-768x768.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ChatGPT: AI writes and codes!</title>
		<link>https://mikeshannon.com/chatgpt</link>
		
		<dc:creator><![CDATA[Mike Shannon]]></dc:creator>
		<pubDate>Fri, 16 Dec 2022 04:51:01 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<guid isPermaLink="false">https://mikeshannon.com/?p=624</guid>

					<description><![CDATA[ChatGPT is an AI-based app that is apparently open for people to test and I think is in a sort of preview mode at the moment. So today I tried ...]]></description>
										<content:encoded><![CDATA[
<p>ChatGPT is an AI-based app that is apparently open for people to test and I think is in a sort of preview mode at the moment.</p>



<p>So today I tried ChatGPT and it blew me away! </p>



<p>The idea is you give it a single sentence such as &#8220;Write me a blog post about moons in the solar system&#8221; or &#8220;write a python program to download an XML news feed&#8221; and it replies with what looks like a human generated response.</p>



<p>Awesome! But scary at the same time&#8230;</p>



<p>How good is it? It actually can write really well. And it can code. In multiple programming languages. Python, C#, PHP. Probably more.</p>



<p>Check out the below video of me write a sentence or two and then the app replies back with a detailed, well written response. In some cases to include actual computer code; I tried running a couple of code examples it generated and the code did work on my computer.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="ChatGPT - My first reactions: It writes and it codes!" width="800" height="600" src="https://www.youtube.com/embed/q5Hzk_Ma5uI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Factory Pattern Examples</title>
		<link>https://mikeshannon.com/factory-pattern-examples</link>
		
		<dc:creator><![CDATA[Mike Shannon]]></dc:creator>
		<pubDate>Sun, 30 Oct 2022 19:09:05 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<guid isPermaLink="false">https://mikeshannon.com/?p=500</guid>

					<description><![CDATA[The factory pattern is a software design pattern where an object of a particular type is returned based on some provided information and without specifying the exact class. Why use ...]]></description>
										<content:encoded><![CDATA[
<p>The factory pattern is a software design pattern where an object of a particular type is returned based on some provided information and without specifying the exact class.</p>



<h2>Why use the Factory pattern? </h2>



<p>Use the factory pattern when you need to provide a way for someone (a consumer or some client code) to use an object without needing to know how that object is created or it&#8217;s dependencies.</p>



<p>The consumer only needs to provide some information to get started using the class object and not the exact class their looking for. </p>



<p>Since the Factory pattern removes the need for a consumer to instantiate class objects, the resulting code becomes less coupled and easier to extend.</p>



<h2>A simple example</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class HandlesSmallFiles {
}

class HandlesLargeFiles {
}

class Factory {
    function generateObject($string) {
        switch($string){
            case "S":
                return new HandlesSmallFiles();
            case "L":
                return new HandlesLargeFiles();
        }
    }
}

$factory = new Factory();
$object = $factory->generateObject("L");
print get_class($object) . "\n";
$object = $factory->generateObject("S");
print get_class($object) . "\n";</pre>



<p>And the output is</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">HandlesLargeFiles
HandlesSmallFiles</pre>



<p>The above example is meant to illustrate the factory concept. We provide either an &#8220;S&#8221; or an &#8220;L&#8221; as the information about what object we want, and then the factory delivers the corresponding object.</p>



<p>However, the design isn&#8217;t great because the Factory class is not open to extension and would require modification. In other words, if you wanted to have a new case to handle medium size files, we would have to edit the Factory class. And this could be painful to regression test all the areas in the application where the Factory class was used.</p>



<h2>An example providing a little more flexibility</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?php

interface FileEncrypter {
    function encrypt();
}

class SmallFileEncrypter implements FileEncrypter {
    private $filename;
    function __construct(string $filename) {
        $this->filename = $filename;
    }
    public function encrypt() {
        return "Now encrypting a small file in memory '".$this->filename."'\n";
    }
}

class LargeFileEncrypter implements FileEncrypter {
    private $filename;
    function __construct(string $filename) {
        $this->filename = $filename;
    }
    public function encrypt() {
        return "Now splitting up '".$this->filename."' into small chunks and encrypting each one\n";
    }
}

abstract class FileEncrypterFactory {
    abstract function getFileEncrypter(): FileEncrypter;
    function doFactoryWork() {
        $encrypter = $this->getFileEncrypter();
        return "FilesFactory: " . $encrypter->encrypt();
    }
}

class SmallFileEncrypterFactory extends FileEncrypterFactory {
    private $filename;
    function __construct(string $filename) {
        $this->filename = $filename;
    }
    function getFileEncrypter(): FileEncrypter {
        return new SmallFileEncrypter($this->filename);
    }
}

class LargeFileEncrypterFactory extends FileEncrypterFactory {
    private $filename;
    function __construct(string $filename) {
        $this->filename = $filename;
    }
    function getFileEncrypter(): FileEncrypter {
        return new LargeFileEncrypter($this->filename);
    }
}

function client(FileEncrypterFactory $factory) {
    print "Now running doFactoryWork() on a ".get_class($factory)." object\n"
        . $factory->doFactoryWork();
}

client(new SmallFileEncrypterFactory("smallfile.txt"));
client(new LargeFileEncrypterFactory("largefile.mp4"));</pre>



<p>And the output is</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Now running doFactoryWork() on a SmallFileEncrypterFactory object
FilesFactory: Now encrypting a small file in memory 'smallfile.txt'
Now running doFactoryWork() on a LargeFileEncrypterFactory object
FilesFactory: Now splitting up 'largefile.mp4' into small chunks and encrypting each one</pre>



<p>In the above example, we are encrypting two files, one small text file and one large mp4 file.</p>



<p>And we have two factory classes, SmallFileEncrypterFactory and LargeFileEncrypterFactory, each for handling small and large files respectively. Both are independent of each other, however both implement the FileEncrypterFactory interface. </p>



<p>We also have a SmallFileEncrypter and LargeFileEncrypterclass both implementing the FileEncrypter interface. These two classes represent the objects the factories create.</p>



<h3>The flow happens like this</h3>



<ul><li>Line 60, where the client() function calls SmallFileEncrypterFactory, the doFactoryWork() method is called on that object.</li><li>doFactoryWork() calls getFileEncrypter() which then returns the SmallFileEncrypter object. So, now our factory has created the intended object to handle encrypting small files.</li><li>Then that SmallFileEncrypter object&#8217;s encrypt() method is run and does the encryption work it needs to do.</li></ul>



<p>The same flow happens for the LargeFileEncrypterFactory call on line 61, resulting in the encrypt() method run on the LargeFileEncrypter object. But in that case the the intent is that a large file is split into smaller chunks and maybe those chunks are swapped to disk unlike the small files that may be encrypted only in memory.</p>



<h3>Why take this approach?</h3>



<ul><li>The client() function only needs to know about the abstract FileEncrypterFactory class and does not need to know about any particular factory; it accepts any type of factory that extends (inherits) the FileEncrypterFactory class.<ul><li>An abstract class was used in this example because that let&#8217;s us have just one default implementation of the doFactoryWork() method for all factories.</li></ul></li><li>If we wanted to have another factory, perhaps for encrypting .zip files, we could create that new factory and a corresponding ZipFilesFactory class and adjust the calls to client(). No need to adjust the other already created classes.</li><li>The factory classes only need to know about the FileEncrypter interface and can return any kind of class object that implements File.</li></ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Software Interview Question: Test if two strings are an Anagram of each other</title>
		<link>https://mikeshannon.com/anagram-test</link>
		
		<dc:creator><![CDATA[Mike Shannon]]></dc:creator>
		<pubDate>Sat, 29 Oct 2022 04:10:30 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<guid isPermaLink="false">https://mikeshannon.com/?p=502</guid>

					<description><![CDATA[I was asked this question during a whiteboarding session while interview for a software engineering job: Test if two strings are an anagram of each other. What is an anagram? ...]]></description>
										<content:encoded><![CDATA[
<p>I was asked this question during a whiteboarding session while interview for a software engineering job:</p>



<p>Test if two strings are an anagram of each other.</p>



<h2>What is an anagram?</h2>



<p>I didn&#8217;t know what anagram meant, so I asked the interviewer to define it for me.</p>



<p><strong>An anagram is where two strings have the same frequency of letters in them. For example &#8220;abc&#8221; and bac&#8221; are anagrams of each other. But &#8220;abc&#8221; and &#8220;aabc&#8221; are not because the former has one &#8220;a&#8221; and the latter has two.</strong></p>



<p>Anyhow, I was able to answer the question and I think this contributed to me landing the job offer.</p>



<p>And I can say for sure if you don’t know something that you think might be important to solving whatever problem you are faced with (even when on the spot), don’t feel afraid to speak up and ask questions. A hiring manager wants to see you interacting and how you think.</p>



<p>Here is a video of me coding and explaining the solution.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Software Engineering Interview Question: Test if two strings are an Anagram of each other" width="800" height="450" src="https://www.youtube.com/embed/o3pBT0n35s4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Here is the code from the above video with slight modification to test the positive and negative case:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * Anagram example: "emike", "eemik"
 * 
 * This function will return true if the two strings have the same frquency of letters
 */

function isAnagram($string1, $string2) {

    if(strlen($string1) != strlen($string2)) return false;

    $a1 = [];
    $a2 = [];

    // count letter frquency of string1
    foreach(str_split($string1) as $key => $value) {
        if(!isset($a1[$value])) $a1[$value] = 0;
        $a1[$value]++;
    }

    // count letter frquency of string1
    foreach(str_split($string2) as $key => $value) {
        if(!isset($a2[$value])) $a2[$value] = 0;
        $a2[$value]++;
    }

    // compare the letter frquency between the two strings
    foreach($a1 as $key => $value) {
        if(!isset($a2[$key])) return false;
        if($a1[$key] != $a2[$key]) return false;
    }

    return true;
}

if(isAnagram("kmgke", "emikk")) print "is anagram\n"; else print "not anagram\n";
if(isAnagram("emike", "eemik")) print "is anagram\n"; else print "not anagram\n";</pre>



<p>Then the output looks like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">not anagram
is anagram</pre>



<p>And by the way, I&#8217;ve since learned the count_chars PHP function performs the anagram test a little faster than the above solution and with only a single line of code (line 2).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">function isAnagram3($string1, $string2) {
    return(count_chars($string1, 1) == count_chars($string2, 1));
}</pre>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Observer Pattern Examples</title>
		<link>https://mikeshannon.com/observer-pattern-examples</link>
		
		<dc:creator><![CDATA[Mike Shannon]]></dc:creator>
		<pubDate>Mon, 24 Oct 2022 06:15:00 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<guid isPermaLink="false">https://mikeshannon.com/?p=486</guid>

					<description><![CDATA[The Observer pattern is a software design pattern that is a good fit for situations where there is one thing that needs to send a message to many other things. ...]]></description>
										<content:encoded><![CDATA[
<p>The Observer pattern is a software design pattern that is a good fit for situations where there is one thing that needs to send a message to many other things. </p>



<p>Said differently, it&#8217;s where one publisher updates one or many subscribers (or &#8220;observers&#8221;).</p>



<p>Here is a simple example</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?php

class Observer {
    function __construct($string) {
        $this->name = $string;
    }
    function update($string) {
        print $this->name . " received message: '" . $string . "'\n";
    }
}

class Publisher {
    private $subscribers = [];
    function add(Observer $observer) {
        array_push($this->subscribers, $observer);
    }
    function sendMessage($string) {
        foreach($this->subscribers as $key => $observer) {
            $observer->update($string);
        }
    }
}

$publisher = new Publisher();
$observer1 = new Observer("Observer 1");
$publisher->add($observer1);
$observer2 = new Observer("Observer 2");
$publisher->add($observer2);
$publisher->sendMessage("Hello!");</pre>



<p>And the output looks like&#8230;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Observer 1 received message: 'Hello!'
Observer 2 received message: 'Hello!'</pre>



<p>In the above example, we start by creating a Publisher object. Then create an Observer object, passing it a string &#8220;Observer 1&#8221; as it&#8217;s name. Then we pass the Observer object to the Publisher via the Publisher&#8217;s add() function. The add() function then pushes the Observer onto an array of $subscribers. Meaning that we&#8217;ve saved or &#8220;subscribed&#8221; the Observer.</p>



<p>We do it again with a second Observer object. </p>



<p>And now we have two Observers subscribed to the Publisher.</p>



<p>Then we call the sendMessage() function on the Publisher object (and pass it a message string &#8220;Hello!&#8221;), which loops through the array of $subscribers (Observers) and calls their update() function, passing it the message string.</p>



<p>And the result is each Observer prints it&#8217;s name and the message that was sent by the Publisher.</p>



<p>Nice!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Decorator Pattern Examples</title>
		<link>https://mikeshannon.com/decorator-pattern-examples</link>
		
		<dc:creator><![CDATA[Mike Shannon]]></dc:creator>
		<pubDate>Sat, 22 Oct 2022 11:29:00 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<guid isPermaLink="false">https://mikeshannon.com/?p=418</guid>

					<description><![CDATA[The Decorator pattern is useful when you want to add some behavior to an object (or compose combinations of behavior) at run time but without adding that same behavior to ...]]></description>
										<content:encoded><![CDATA[
<p>The Decorator pattern is useful when you want to add some behavior to an object (or compose combinations of behavior) at run time but without adding that same behavior to an entire class of objects.</p>



<p>I think this capability can be very useful especially when only parts of an application might need that change and not all of it. </p>



<p>Let&#8217;s see some examples&#8230;</p>



<h2>Lets take the Coffee Shop example</h2>



<p>The example I see often used on many websites is where a coffee shop offers coffee and a number of extras like milk, sugar, spices, etc. that could be added to a cup of coffee. </p>



<ul><li>To avoid class explosion (making a class for every possible coffee combination), the coffee shop implements the Decorator pattern to compose whatever permutation of coffee a customer might ask for. </li><li>They treat each of those parts as a &#8220;Beverage&#8221; (implementing a Beverage interface). To me that makes no sense, because sugar and spices aren&#8217;t a beverage. </li><li>Anyway, they start with coffee object. Then inject that into sugar object. Then inject that into a milk object. And so on. Until the stack of objects unwinds and ads up a final price and description. To me this example isn&#8217;t very practical. Yes you could compose objects at run time any way you want but here it seems overkill. Instead why not just have an array of objects passed to a coffee object, then iterate through and add up their prices and descriptions vs use the Decorator pattern.</li></ul>



<h2>A more practical Decorator example</h2>



<p>I think what&#8217;s more practical is extending an object (at run time) with a wrapper class, like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?php

interface Logger {
    function log();
}

class SimpleLogger implements Logger {
    function log() {
        print "The info to log...\n";
    }
}

class VerboseLogger implements Logger {
    private $logger;
    function __construct(Logger $logger = null) {
        $this->logger = $logger;
    }
    function log() {
        print "Adding some additional info before...\n";
        if(isset($this->logger)) $this->logger->log();
        print "And adding additional info after\n";
    }
}

$simplelogger = new SimpleLogger();
$verboselogger = new VerboseLogger($simplelogger);
$verboselogger->log();</pre>



<p>And the output is</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Adding some additonal info before...
The info to log...
And adding additional info after</pre>



<p>In the above example a SimpleLogger object is created and then injected into a VerboseLogger object. The latter wraps the former and adds some additional logging info (before and after) without adjusting the SimpleLogger class in any way.</p>



<p>I think this example is more practical than the coffee shop example because it could be that the SimpleLogger is already used many places within an application. And you may only want to extend a subset of those objects with VerboseLogger. Because you only need additional info logged at certain points. </p>



<h2>Deprecating old code</h2>



<p>Another example I&#8217;ve heard of (very similar to the above example) is to wrap old code that needs to be deprecated in some places and not in others. Let&#8217;s say we create a version two of our SimpleLogger class called &#8220;SimpleLoggerV2&#8221;. We might only want parts of the system to be adjusted rather than the whole thing to reduce risk of things breaking. By wrapping the old code with a decorator the old behavior can be adjusted or even ignored.</p>



<h2>The Decorator Pattern is cool!</h2>



<p>Whatever the case the Decorator pattern is nice and gives us flexibility to add behavior to existing objects at run time. And helps when we need to adjust behavior across part of a system vs all of it.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Strategy Pattern Examples</title>
		<link>https://mikeshannon.com/strategy-pattern-examples</link>
		
		<dc:creator><![CDATA[Mike Shannon]]></dc:creator>
		<pubDate>Sat, 22 Oct 2022 05:47:59 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<guid isPermaLink="false">https://mikeshannon.com/?p=383</guid>

					<description><![CDATA[What is the strategy pattern? The Strategy pattern is a software design pattern that lets a class change its behavior at run time; helping to keep classes decoupled and re-usable. ...]]></description>
										<content:encoded><![CDATA[
<p>What is the strategy pattern? </p>



<p><strong>The Strategy pattern is a software design pattern that lets a class change its behavior at run time; helping to keep classes decoupled and re-usable.</strong></p>



<p>Run time? Behavior?</p>



<p>I really like this description from Stackoverflow which seems like a real world use</p>



<p>(those duck and animal examples just don&#8217;t cut it for me!):</p>



<figure class="wp-block-pullquote"><blockquote><p>&#8220;A game where we can have different characters and each character can have multiple weapons to attack but at a time can use only one weapon&#8221;</p><cite><a href="https://stackoverflow.com/questions/370258/real-world-example-of-the-strategy-pattern#:~:text=A%20good%20example%20of%20strategy,can%20use%20only%20one%20weapon." target="_blank" rel="noreferrer noopener">Stackoverflow</a></cite></blockquote></figure>



<p>In this case, we could have a character class and also some weapon classes like gun or sword. The weapon classes may subscribed to an interface that says each weapon needs to implement an Attack() method. That way, the character class only needs to know about the interface and could accept any type of weapon at a given time.</p>



<p>Let&#8217;s take another example&#8230;</p>



<h2>A calculator that wants to log it&#8217;s activity</h2>



<p>Suppose you have a calculator class and all it does is crunch numbers. Add, subtract, etc.</p>



<p>You then want to extend that class to log usage to a file or a database.</p>



<p><strong>Should you add that new behavior to your calculator class?</strong> You could but that would start to bloat your calculator class.</p>



<p><strong>What about letting sub-classes (that inherit the Calculator class) implement logging behavior?</strong> Again, you could do this but the problem is what happens when two different sub classes want to log their activity. Now you end up with the same code possibly in two locations. Not good!</p>



<p><strong>Instead let&#8217;s use the Strategy pattern! </strong>We will create an interface just for the logging and tell our Calculator class it should know about that interface. This allows our Calculator class to leverage any logging class that wants to implement that interface. And our Calculator class doesn&#8217;t need to know details about logging, just that it can log.</p>



<p>Here is some code (PHP) to illustrate:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?php

interface Loger {
    function log();
}

class FileLoger implements Loger {
    function log() {
        print "now logging info to a file...\n";
    }
}

class DatabaseLoger implements Loger {
    function log() {
        print "now logging info to a database...\n";
    }
}

class Calculator {
    private $log;

    function __construct(Loger $log) {
        $this->log = $log;
    }

    function log() {
        $this->log->log();
    }
}

class ScientificCalculator extends Calculator {
    function someAdvancedFeature() {
        // tbd...
    }
}

$fileloger = new FileLoger();
$calculator = new Calculator($fileloger);
$calculator->log();

$fileloger2 = new DatabaseLoger();
$calculator2 = new Calculator($fileloger2);
$calculator2->log();</pre>



<p>And here is the output</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">now logging info to a file...
now logging info to a database...</pre>



<p>In the above code we have a Calculator class that has a private member variable $log. </p>



<p>We also have a Loger interface with concrete implementations FileLoger and DatabaseLoger to log to files and to a database, respectively.</p>



<p>When we create a new Calculator object, we also first created a FileLoger object and passed that into the constructor of the Calculator object. And our Calculator constructor is expecting a variable of interface type Loger; it doesn&#8217;t care about any concrete implementations of Loger. The Calculator class could accept a FileLoger or DatabaseLoger object and it doesn&#8217;t mater. It only knows about the Loger interface.</p>



<p>So the constructor stores the local $log variable to it&#8217;s private $log variable.</p>



<p>Then later we call the Calculator&#8217;s log() function, which in turn calls the private $log variable&#8217;s log() function, which again is defined in the Loger interface and that&#8217;s all the Calculator class knows about. It doesn&#8217;t care about how anyone implemented the log() function.</p>



<p>And we can create another Calculator after that with a different concrete implementation of the Loger interface and log to a Database. Or someone could create another concrete implementation to log to an API.</p>



<p>What&#8217;s also nice is we&#8217;ve got a ScientificCalculator class that inherits from the Calculator class and now it too can leverage objects that implement Loger and begin logging usage.  It&#8217;s not shown in the code, but if you pass a Loger object into the  ScientificCalculator constructor you&#8217;d get the same behavior as the Calculator object.</p>



<h2>Decrypting a file based on file size</h2>



<p>I like <a href="https://stackoverflow.com/questions/370258/real-world-example-of-the-strategy-pattern" data-type="URL" data-id="https://stackoverflow.com/questions/370258/real-world-example-of-the-strategy-pattern">this example from a Stackoverflow contributor</a> who actually used the Factory pattern along with the Strategy pattern to determine how to do data encryption (the algorithm that can change at run time) based on the size of the file in question.</p>



<p>I&#8217;ve copied and re-written the example here (and the language is Java):</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">File file = getFile();
Cipher c = CipherFactory.getCipher( file.size() );
c.performAction();

interface Cipher  {
    public void performAction();
}

class InMemory implements Cipher { 
    public void performAction() {
        // load in byte[] ....
    }
}

class SwaptToDisk implements Cipher { 
    public void performAction() {
        // swapt partial results to file.
    }
}</pre>



<p>In the above example</p>



<ul><li>For small files less than 1 gigabyte, the InMemory class should be used to performAction(); meaning the entire file is read and kept in memory and the decryption is done there. </li><li>Larger files should use the SwapToDisk class to performAction(); meaning parts of the file are read to memory and partial encrypted results are stored in tmp files.</li><li>Line 2 is the Factory which will get the correct class object based on the file size. The Factory implementation is not shown and this line is just to give you an idea the Factory does exist.</li><li>And line 3 is where the rubber meets the road and the Strategy pattern is used to run the performAction method (from the appropriate object).</li></ul>



<p>So, this example differs slightly from the Calculator. With the Calculator we injected the Logger type into the Calculator object manually at run time. With the decryption example things are more dynamic and it&#8217;s the file size that determines which implementation (which object) of performAction() to use.</p>



<p>And now we can see the power of the strategy pattern. Super useful. <strong>It helps to keep our classes decoupled and re-usable.</strong></p>



<p>Very cool! <img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>An example of how to find and replace recursively using sed</title>
		<link>https://mikeshannon.com/find-and-replace-using-sed</link>
		
		<dc:creator><![CDATA[Mike Shannon]]></dc:creator>
		<pubDate>Fri, 14 Oct 2022 15:39:23 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<guid isPermaLink="false">https://mikeshannon.com/?p=339</guid>

					<description><![CDATA[I recently needed to find and replace a string of text inside a large text file. The file was a database export from mysql (from a mysqldump command I had ...]]></description>
										<content:encoded><![CDATA[
<p>I recently needed to find and replace a string of text inside a large text file.</p>



<p>The file was a database export from mysql (from a mysqldump command I had run).</p>



<p>And if you&#8217;ve ever run a mysqldump command you know those files can be pretty large / long.</p>



<p>It would be possible to move the file to your desktop, open it up in a text editor and do a find and replace, then move it back to the server. But large files take time to transfer and open up. And then you have to worry that did your text editor do something like add weird line endings to the file and will the file still work when it gets re-imported back to mysql?</p>



<p>So, why worry or do that when you have sed?</p>



<p><a rel="noreferrer noopener" href="https://www.gnu.org/software/sed/manual/sed.html" data-type="URL" data-id="https://www.gnu.org/software/sed/manual/sed.html" target="_blank">sed</a> is a command line tool found in linux and let&#8217;s us modify text files (or more specifically &#8220;streams&#8221; of input).</p>



<p>In the below code example I am running a find command from the current directory (the &#8220;./&#8221;) and then telling find to run the sed command. </p>



<p>The sed command then looks at each file (the &#8220;{}&#8221;) that find picks up and in this case, replaces the string &#8220;olddomain.com&#8221; with &#8220;newdomain.com&#8221; (the &#8220;s&#8221; right before the &#8220;/&#8221;) all throughout that file. And it does that replacing &#8220;in-place&#8221; (the -i parameter) rather than printing the edited text to the console.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="bash" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">find ./ -type f -exec sed -i -e 's/olddomain.com/newdomain.com/g' {} \;</pre>



<p>In my case, I was moving a WordPress website from one domain to another. </p>



<p>And actually, I ran the above code against the mysqldump file as well as the entire WordPress directory of files so that any reference to the domain would be found and replaced. Nice!</p>



<p>(WordPress likes to hardcode the domain being used into not only the database but also files, yuck)</p>



<p>However, I&#8217;m sure sed could be used for lots of other file or stream editing beyond WordPress migrations.</p>



<p>Happy sed-ing <img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How our Universe might be inside a Black Hole</title>
		<link>https://mikeshannon.com/universe-inside-a-black-hole</link>
		
		<dc:creator><![CDATA[Mike Shannon]]></dc:creator>
		<pubDate>Sun, 09 Oct 2022 05:10:21 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<guid isPermaLink="false">https://mikeshannon.com/?p=331</guid>

					<description><![CDATA[My mind was blown when I first heard about this idea. Does our universe reside inside a black hole? Some people think so, including me. I think at least it&#8217;s ...]]></description>
										<content:encoded><![CDATA[
<p>My mind was blown when I first heard about this idea.</p>



<p><strong>Does our universe reside inside a black hole?</strong></p>



<p>Some people think so, including me. I think at least it&#8217;s possible!</p>



<p>I thought it was so interesting I had to make a video&#8230;</p>



<p>Here is a video of me illustrating the main idea as I see it: since we know our universe is expanding, then if the space inside a black hole is also expanding (including space within the singularity) then they might be one in the same.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How our Universe might be inside a Black Hole" width="800" height="600" src="https://www.youtube.com/embed/0Q3z76QN0DQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Concurrency vs Parallelism. What’s the difference?</title>
		<link>https://mikeshannon.com/concurrency-vs-parallelism</link>
		
		<dc:creator><![CDATA[Mike Shannon]]></dc:creator>
		<pubDate>Mon, 03 Oct 2022 00:35:27 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<guid isPermaLink="false">https://mikeshannon.com/?p=254</guid>

					<description><![CDATA[Concurrency and Parallelism are not the same. Think of it like this: Concurrency is how you manage multiple things that need to run at the same time. Parallelism is running ...]]></description>
										<content:encoded><![CDATA[
<p>Concurrency and Parallelism are not the same.</p>



<p>Think of it like this:</p>



<p><strong>Concurrency is how you manage multiple things that need to run at the same time. Parallelism is running multiple things at the same time.</strong></p>



<p>So, manage vs run.</p>



<p><strong>With Concurrency</strong>, you may have two things that you need to get done but only one resource available to do them. Sort of like when one person is multitasking.</p>



<p>For example, you are cooking pasta for dinner!</p>



<figure class="wp-block-image size-full is-resized"><img loading="lazy" src="https://mikeshannon.com/wp-content/uploads/2022/10/fork-and-noodles.jpg" alt="" class="wp-image-311" width="321" height="401" srcset="https://mikeshannon.com/wp-content/uploads/2022/10/fork-and-noodles.jpg 640w, https://mikeshannon.com/wp-content/uploads/2022/10/fork-and-noodles-240x300.jpg 240w" sizes="(max-width: 321px) 100vw, 321px" /></figure>



<p>You fill a pot full of water and put it on the stove to heat up. While the water is heating up you don’t wait for it to boil and move to another task. You select the noodles you want to cook and begin preparing the sauce. Then the water is boiling. Stop with the sauce and the noodles. And then back to the sauce and other things while the noodles cook.</p>



<p>You’ve taken multiple things (cooking noodles, preparing the sauce) and broken them up into smaller bits allowing you to do things concurrently instead of in sequence (finish the noodles and then finish the sauce), because in sequence would take way too long, right?</p>



<p><strong>On the other hand, with Parallelism</strong>,  you may have two things to do and have two resources to do them. One resource per thing. <em>Or two people in the kitchen: one person cooking the noodles and one person preparing the sauce. That’s parallelism.</em></p>



<p>Are they the same? No!</p>



<p>Manage multiple things at the same time (concurrency) vs have multiple things run at the same time (parallelism).</p>



<p>Here is a 30 min video by Rob Pike explaining the difference. He uses the Go programming language to illustrate his ideas. But the ideas are not language dependent.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Concurrency is not Parallelism by Rob Pike" width="800" height="450" src="https://www.youtube.com/embed/oV9rvDllKEg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<h2>What is Concurrency? Give me a code example!</h2>



<p>You may or may not get the Concurrency examples that Rob provides in his above video.</p>



<p>To better understand concurrency with a code example we can look at the idea of async await.</p>



<p>Different languages like JavaScript and C# (there are others) allow you to call a function and run other code while that function runs in case it happens to run long. Then of course once that long running function returns the other code pauses allowing your calling code to do whatever it needs to. Then your other code resumes and your program continues on.</p>



<h3>Here is a JavaScript example of Concurrency:</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import fetch from 'node-fetch';

async function cook() {
  await fetch("https://mikeshannon.com/heatTheWater");
  console.log("The water is now boiling");
}

cook();
console.log("Prepare the sauce");</pre>



<p>In the above example, even though the console.log statement looks like it will complete after the cook() function, the console.log() will complete <strong>before</strong> the cook() function. That&#8217;s because we assume the cook() function is long running due to it calling fetch() and waiting for the website to return a response.</p>



<p>The &#8220;async&#8221; before the function keyword and the &#8220;await&#8221; before our fetch() command tells our program to begin running other things (<em>in this case the console.log(&#8220;Prepare the sauce&#8221;)</em>) while the fetch() is waiting on a response.</p>



<p>Running the code we get&#8230;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Prepare the sauce
The water is now boiling</pre>



<h3>We can take the example a little farther and cook some turkey pasta!</h3>



<p>In this example we setup what we think will be long running tasks into async await functions: Heating the water, cooking the noodles and cooking the turkey. The other tasks of preparing the sauce and strainer are quick and won&#8217;t take as long.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import fetch from 'node-fetch';

async function heatTheWater() {
    console.log("Starting to heat the water");
    await fetch("https://mikeshannon.com/heatTheWater");
    console.log("The water is boiling");
}

async function cookTheNoodles() {
    console.log("Adding noodles");
    await fetch("https://mikeshannon.com/cookTheNoodles");
    console.log("Noodles are done cooking");
}

async function cookTheTurkey() {
    console.log("Starting to cook the turkey");
    await fetch("https://mikeshannon.com/cookTheTurkey");
    console.log("Turkey is done cooking");
}

heatTheWater().then(() => cookTheNoodles());
console.log("Prepare the sauce");
console.log("Prepare the strainer");
cookTheTurkey();</pre>



<p>And let&#8217;s run it and get the response&#8230;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Starting to heat the water
Prepare the sauce
Prepare the strainer       
Starting to cook the turkey
The water is boiling
Adding noodles
Turkey is done cooking
Noodles are done cooking</pre>



<p>Instead of doing one activity after another in sequence: heating the water, waiting for it to boil and then cooking the noodles, and then preparing the sauce and then turkey&#8230; our program decided to break things up and multitask (and act with concurrency) to make the most of it&#8217;s time (using async await in the code):</p>



<p>You can see from the response the program started with heating the water but that typically takes some time to start boiling. In the meantime it prepared the sauce and the strainer. Still waiting for the water to boil, it started cooking the turkey. Then the water started boiling, so right away it added the noodles. Then the turkey finished cooking. And finally the noodles finished cooking too.</p>



<p>Whew what a meal!</p>



<p>(Heads up each run may result in a slightly different response based on how long each fetch() request takes&#8230; but I think you get the idea)</p>



<p>Another example of a long running request is when a call is made to a database or any third party service and in that case you may not want that waiting to block your other code from running. And by leveraging the concept of concurrency it helps to make the most of what you have.</p>



<p>Concurrency let’s your code multitask. Whether or not it has one or multiple CPUs to run on. <br></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
