<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by James Rowa on Medium]]></title>
        <description><![CDATA[Stories by James Rowa on Medium]]></description>
        <link>https://medium.com/@jrowah?source=rss-58b16ac491fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FrPK2O5kCQ3v837E3FrYLw.png</url>
            <title>Stories by James Rowa on Medium</title>
            <link>https://medium.com/@jrowah?source=rss-58b16ac491fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:23:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jrowah/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Phoenix Contexts]]></title>
            <link>https://medium.com/@jrowah/contexts-with-phoenix-c83d93bbfd9a?source=rss-58b16ac491fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c83d93bbfd9a</guid>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[mvc-frameworks]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[James Rowa]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 11:59:38 GMT</pubDate>
            <atom:updated>2023-01-31T12:03:47.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwPsGSfzmU3skJvimoIz2Q.png" /></figure><p>I recently dived into Elixir and found out how fun and easy to understand the language is. I want to learn its framework Phoenix by building a full stack travel blog application. I use this project to learn Phoenix contexts and authentication. Let’s go!</p><p>Here is what we are going to do in the first part of this project:</p><p>1. Set up a new Phoenix project</p><p>2. Generate an Accounts context</p><p>3. Generate an Blog context with a Post model</p><p>4. Generate a Comment model inside the Blog context</p><p>5. Create a comments controller</p><p>6. Create a comments form, load and display comments</p><p>All the completed code for this project can be found on this <a href="https://github.com/rowah/travel_blog">repository</a>. Clone and switch to the comment_feature branch for the code. The main branch has authentication implemented.</p><p>To get started, we will open the terminal and change directory to wherever you want to create your project. Once there, run the command below to create a new Phoenix project called travel_blog.</p><pre>$ mix phx.new travel_blog</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*8SR8mQrZz6jj7BFeL4cwQg.png" /></figure><p>Once created and all the dependencies installed, let us cd into the travel_blog directory and open it on your text editor by running these on the terminal.</p><pre>$ cd travel_blog<br>$ code .</pre><p>Then configure your database in config/dev.exs and then to create the db, run:</p><pre>$ mix ecto.create</pre><p>Then start the Phoenix app with;</p><pre>$ mix phx.server</pre><p>Open the application in the browser and see the default “Welcome to Phoenix” page. Awesome!</p><p>Let us create our first context. Think of a context as a boundary to decouple and isolate parts of your application. They encapsulate data access and data validation in Phoenix applications.</p><p>The first context we will create is the Accounts context. To do so, run;</p><pre>$ mix phx.gen.context Accounts User users first_name:string last_name:string email:string password_hash:string</pre><p>You should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*GX4jysGGspJTi-0KS26_HA.png" /></figure><p>So here we are creating an Accounts context with a “User” schema and the data table name being “users” with <em>first_name</em>, <em>last_name</em>, <em>email</em>, and <em>password_hash</em>. This generates files like User.ex which is a schema with users tables, accounts.ex which severs as the API boundary and a bunch of other test files.</p><p>Next we need a Post schema. To generate this, we will need to create a Blog context, that will have the posts and comments. I choose to have the two under one context since they will have a connection.</p><p>We’ll use <em>mix phx.gen.html</em> which creates a context module that wraps up Ecto access for creating, updating, and deleting products, along with controllers and template web files (views) for the web interface into our context. We will give our posts a title (string), and a body (text). Run:</p><pre>$ mix phx.gen.html Blog Post posts title:string body:text</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*NstaN-j__btBOkqYWb1M7A.png" /></figure><p>A look into the post.ex shows that it is the post schema that maps to the corresponding db table named posts. There is also the post_controller.ex which is where we will interact with the posts and their associated comments, but through the Blog context module which contains the “blog” functionality. For example, we use the <strong><em>Blog.list_posts </em></strong>to get all the posts, we pass in the post id into the <strong><em>Blog.get_post</em></strong> to get a particular post, and we can create a post using the <strong><em>Blog.create_post</em></strong> function.</p><p>When we open the Blog context module we can see all the functions that are called in the post_controller.ex such as <strong><em>list_posts</em></strong> which looks up and lists all our posts from the db, <strong><em>create_post</em></strong>, <strong><em>get_post</em></strong> which retrieved a single post whose id is passed and son on.</p><p>Then, we need to add the new resource _resources “/posts”, PostController_ into the lib/travel_blog_web/router.ex file.</p><pre>defmodule TravelBlogWeb.Router do<br>  use TravelBlogWeb, :router<br><br>  import TravelBlogWeb.UserAuth<br><br>  pipeline :browser do<br>    plug :accepts, [&quot;html&quot;]<br>    plug :fetch_session<br>    plug :fetch_live_flash<br>    plug :put_root_layout, {TravelBlogWeb.LayoutView, :root}<br>    plug :protect_from_forgery<br>    plug :put_secure_browser_headers<br>    plug :fetch_current_user<br>  end<br><br>  pipeline :api do<br>    plug :accepts, [&quot;json&quot;]<br>  end<br><br>  scope &quot;/&quot;, TravelBlogWeb do<br>    pipe_through :browser<br><br>    get &quot;/&quot;, PageController, :index<br>    resources &quot;/posts&quot;, PostController<br>  end</pre><p>We can now run our migrations once again and start our server again using <em>mix phx.server</em>. We can then navigate to the /posts route and create a new post.</p><p>We can now dive into the more challenging part of our project. We want to create the comments. We are going to include the comments functionality inside the already existing blog context since the two are going to be related. To avoid complication, we use the same post templates we generated through <em>mix phx.gen.html</em> which we used to create the blog context. We are not going to need any web files for the comments so we can go ahead and use the <em>mix phx.gen.context</em> generator with “Blog” as the context and Comment as the schema and comments for the table name. Additionally, our comments need to have a body, and an association with a post and so we will add a “post_id” that will reference the post that each comment will be associated with. So run;</p><pre>$ mix phx.gen.context Blog Comment comments body:string post_id:references:posts</pre><p>Upon running the generator, Phoenix asks if we are sure about creating the schema inside the Blog context and not in one of its own. This is okay in our case since the comments are associated with the Blog, and if we remember we created the Accounts context on its own. When we run the generator, we can see a new comment schema module created along with the associated comments migration. A look into the blog.ex we see some comments functions injected which are going to interact with the comments.</p><p>After defining the relationship between our posts and comments, we need to “link” this relationship by doing some modifications in their schemas. We need to open the lib/travel_blog/blog/comment.ex schema module and add the belongs_to association to the schema.</p><pre>defmodule TravelBlog.Blog.Comment do<br>  use Ecto.Schema<br>  import Ecto.Changeset<br><br>  schema &quot;comments&quot; do<br>    field :body, :string<br>    belongs_to :post, TravelBlog.Blog.Post<br><br>    timestamps()<br>  end<br><br>  @doc false<br>  def changeset(comment, attrs) do<br>    comment<br>    |&gt; cast(attrs, [:body])<br>    |&gt; validate_required([:body])<br>    |&gt; validate_length(:body, min: 2, max: 250)<br>  end<br>end</pre><p>We also need to open the post.ex schema module and add the has_many association with the comments.</p><pre>...<br>schema &quot;posts&quot; do<br>    field :body, :string<br>    field :title, :string<br>    has_many :comments, TravelBlog.Blog.Comment<br><br>    timestamps()<br>  end<br><br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*un2yDsQ2nHQjJW0iatdXqQ.png" /></figure><p>After associating the comments with the posts, we need to ensure that when a post will be deleted, all the comments associated with it will also have to be deleted along with it. To do this, let us go to the migrations that were generated and on_deleted, let us say delete_all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsQOYexpkIcs29IFANgvng.png" /></figure><p>We can then run our migrations;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*rIdn_Y5WnzY6yO1-vKQ2aA.png" /></figure><p>Going back into the blog.ex context module inside of which our comment functions were also created, we notice that the patterns of both create_post and create_comment functions are the same, while the latter will have to take in the post with which the comment it creates will be associated. Therefore, we need to modify the create_comment function to accept the post that we want to associate the comment with. The file path is</p><pre>... <br>def create_comment(%Post{} = post, attrs \\ %{}) do<br>    post<br>    |&gt; Ecto.build_assoc(:comments)<br>    |&gt; Comment.changeset(attrs)<br>    |&gt; Repo.insert()<br>  end<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DyNkvwSwlZ-Z7lryFO7EzA.png" /></figure><p>Remember that when we created the Comment schema module inside the Blog context, we did not generate any of the web files. Therefore, we will need to create our own controller for the comments and later on update the post view to accommodate the creation and display of the comments.</p><p>Inside the controllers directory, let us create a new module comment_controller.ex inside of which we will define our module, and give it a single create function that accepts the connection. We need to pattern matching on the params to get the id of the post, and the comment params (sent over from the comment form after submission).</p><pre>defmodule TravelBlogWeb.CommentController do<br>  use TravelBlogWeb, :controller<br><br>  alias TravelBlog.Blog<br><br>  ##this is what will be sent over from the comment form<br>  def create(conn, %{&quot;post_id&quot; =&gt; post_id, &quot;comment&quot; =&gt; comment_params}) do<br>    post = Blog.get_post!(post_id)<br><br>    #create comment<br>    case Blog.create_comment(post, comment_params) do<br>      {:ok, _comment} -&gt;<br>        conn<br>        |&gt; put_flash(:info, &quot;Comment created successfully&quot;)<br>        |&gt; redirect(to: Routes.post_path(conn, :show, post))<br>      {:error, _changeset} -&gt;<br>      conn<br>      |&gt; put_flash(:info, &quot;Comment creation unsuccessful&quot;)<br>      |&gt; redirect(to: Routes.post_path(conn, :show, post))<br><br>    end<br><br>  end<br>end</pre><p>To get the post that the incoming comment is associated with, we will call the <strong><em>Blog.get_post</em></strong> function which will take in the post id coming with the comment, and then create our comment using a case statement in the Blog.create_comment function that we had already associated with the post. We will then need to pattern match the OK tuple that will be returned if the comment is created successfully and the error tuple returned if the creation fails. If the comment is created, we display a flash message indicating so and redirecting the user to the post path, and if it fails, we will also display an error message and return them to the post path.</p><p>We will then need to go to the router.ex and nest the new CommentController inside the “posts” resource, only specifying the “create” action which is what we set in the controller.</p><pre>...<br> get &quot;/&quot;, PageController, :index<br>    resources &quot;/posts&quot;, PostController do<br>      resources &quot;/comments&quot;, CommentController, only: [:create]<br>    end<br>  end<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FeXVd91AuvKnth0KjVR9iQ.png" /></figure><p>We will the need to add our comments form inside the post’s <em>show.htm.eex</em> template just below the post by defining a new from_for with a @comment_changeset that we will create. We are then posting the form to the new comments path we just created.</p><pre>....<br>&lt;h3&gt;Add a comment&lt;/h3&gt;<br>&lt;%= form_for @comment_changeset, Routes.post_comment_path(@conn, :create, @post), fn f -&gt; %&gt;<br>  &lt;%= label f, :body %&gt;<br>  &lt;%= textarea f, :body %&gt;<br>  &lt;%= error_tag f, :body %&gt;<br>  &lt;div&gt;<br>    &lt;%= submit &quot;Comment&quot; %&gt;<br>  &lt;/div&gt;<br>&lt;% end %&gt;<br>....</pre><p>We then need to create the comment_changeset in the show function inside the post_controller.ex. Calling the Blog.change_comment gets us our comment changeset, which we then pass into the assigns as comment_changeset. We then have to alias Comment so we can use it here without the prefix. The file path is lib/travel_blog_web/controllers/post_controller.</p><pre>....<br>def show(conn, %{&quot;id&quot; =&gt; id}) do<br>    post = Blog.get_post!(id)<br>    comment_changeset = Blog.change_comment(%Comment{})<br>    render(conn, &quot;show.html&quot;, post: post, comment_changeset: comment_changeset)<br>  end<br>....</pre><p>We can then run the server using mix phn.server and go to any of the posts you already created and there we see our comment form. If we try to create a comment, we receive a message that the comment was created but we cannot see it. The reason here is that while we are creating and persisting our comment in the database, we have no way of displaying it on the screen and so we need to modify our views. To do this, we first need to modify the function that we use to get our post to also load the comment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hKe9g-41KnDePo1UwNs1w.png" /></figure><p>Once we are loading the comments like so, we can modify the post’s show.htm.eex template to display all the comment below the post they are associated with. File path: lib/travel_blog_web/templates/posts/show.html.heex</p><pre>...<br>&lt;h3&gt;Comments&lt;/h3&gt;<br>&lt;ul&gt;<br>&lt;%= for comment &lt;- @post.comments do %&gt;<br>  &lt;li class=&quot;comment&quot;&gt;&lt;%= comment.body %&gt;&lt;/li&gt;<br>&lt;% end %&gt;<br>&lt;/ul&gt;<br>...</pre><p>This finally loads all comments just below the post they are associated with plus any other comment created on the particular post, as we can see from the browser.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c83d93bbfd9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String Methods Every JavaScript Developer Should Know]]></title>
            <link>https://medium.com/@jrowah/string-methods-every-javascript-developer-should-know-724b45698799?source=rss-58b16ac491fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/724b45698799</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-string-method]]></category>
            <dc:creator><![CDATA[James Rowa]]></dc:creator>
            <pubDate>Sat, 08 Oct 2022 15:46:34 GMT</pubDate>
            <atom:updated>2022-10-08T15:46:34.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjQEBO7M-fW7AFQvw73Q8A.jpeg" /><figcaption>JavaScript String Methods</figcaption></figure><p>In Javascript, a string is a primitive data type that represent a sequence of characters including letters, numbers, and symbols. JavaScript provides some useful functions (methods) that facilitate operations on strings when programming. This article outlines the most essential string methods that you should know. Unless in examples specified, each method uses variables assigned at the beginning; firstName, secondName, and fullName.</p><h3>1. charAt()</h3><p>The charAt method takes in an index and returns a new string that contains the single UTF-16 code (specific character) at the index location of whatever index that was passed in. The methods checks if the index passed in matches those that are within the length of the calling string and returns the character. If the index is outside of the string’s length, returns an empty string, and if no argument is passed it returns the character at the zero index.</p><pre>const firstName = &quot;James&quot;;</pre><pre>const initialsIndex = 0;</pre><pre>const nameInitial = firstName.charAt(initialsIndex);</pre><pre>console.log(nameInitial); <em>//J</em></pre><pre>console.log(firstName.charAt(firstName.length - 1)); <em>//s</em></pre><h3>2. charCodeAt()</h3><p>The method takes in an index value and returns an integer for the UTF-16 value of the character where the passed character is at. Just like the charAt method, the charCodeAt checks if the passed index matches any index in the string it is called on and returns the UTF-16 integer value (character code) of the character at that index. For character code greater that 655536, the charCodeAt(i+1) gets the other half of the value pair. An index that is outside of the string’s length returns NaN.</p><pre>const nameInitialCode = firstName.charCodeAt(initialsIndex);</pre><pre>console.log(</pre><pre>`The ASCII code for first letter of my first name is ${nameInitialCode}`</pre><pre>); //The ASCII code for first letter of my first name is 74</pre><pre>console.log(firstName.charCodeAt(firstName.length - 1)); //115</pre><h3>3. concat()</h3><p>The concat() method takes in multiple strings, joins them together, otherwise called string concatenation and produces a single string. It joins the strings passed as arguments to the string it is called on without changing the original strings. Non-string type arguments passed on the method get converted to string values before concatenating.</p><pre>const secondName = &quot;Rowa&quot;;</pre><pre>const fullName = firstName.concat(&quot; &quot;, secondName);</pre><pre>console.log(fullName); <em>//James Rowa</em></pre><pre>console.log(fullName.concat([&quot;Nairobi&quot;, &quot;Kenya&quot;])); <em>//James RowaNairobi,Kenya</em></pre><h3>4. includes()</h3><p>This method carries out a case-sensitive search on the string it is called on to determine the presence or absence of the string passed in as argument and returns either true or false depending on the outcome of the search. The method takes in either the string to be searched for, but can take an additional optional argument (position) which is the position within the string at which the search begins. By default the position is 0.</p><p>The search is done from the default position and returns every character that matches the string passed as argument. If the returned characters match the input string in its exact order, the method returns true, otherwise it returns false.</p><pre>console.log(fullName.includes(&quot;jam&quot;));<em>//false (case-sensitivity)</em></pre><pre>console.log(fullName.includes(&quot;Jam&quot;));<em>//true<br></em>console.log(fullName.includes(&quot;Jam&quot;, 1));//false (position 1)<br>console.log(fullName.includes(&quot;R&quot;));<em>//TRUE</em></pre><h3>5. indexOf()</h3><p>The methods takes in a substring as an argument that is to be searched for and searches the entire string it is called on for the first occurrence of the substring being searched for and returns the index value of the first occurrence. If the substring doesn’t exist, it returns -1. With a second argument as a number, the indexOf method returns the first occurrence of the argument substring at an index equal to or greater than the number passed.</p><pre>const sentence =</pre><pre>&quot;My eldest brother, also called Rowa, and I share the name Rowa&quot;;</pre><pre>const sharedName = &quot;Rowa&quot;;</pre><pre>const namesFirstIndex = sentence.indexOf(sharedName);</pre><pre>console.log(</pre><pre>`In the sentence, the name ${sharedName.toLocaleUpperCase()} appears first at index ${namesFirstIndex} and also at index ${sentence.indexOf(</pre><pre>sharedName,</pre><pre>namesFirstIndex + 1</pre><pre>)}.`</pre><pre>); //In the sentence, the name ROWA appears first at index 31 and also at index 58.</pre><pre><em>// NB: we add one to the index the word first appears so that the second search just assumed the already existing first name and searches going forward from index 39.</em></pre><pre>console.log(sentence.indexOf());//-1<br>console.log(sentence.indexOf(&quot;&quot;));//0<br>console.log(sentence.indexOf(&quot;rowa&quot;));//-1 name with lowercase r is non-existent in the sentence<br>console.log(sentence.indexOf(&quot; &quot;)); //2 space exists in the second index</pre><p>Additional information on the method, especially a more detailed explanation on the parameters it take can be found on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf">MDN documentation</a>.</p><h3>6. match()</h3><p>The match() method is used to match a string against a RegExp and retrieve the result of the match. The passed in parameter gets converted into a RegExp using the new RegExp(parameter) if it is not a RegExp object. Calling the match() method without passing in a parameter returns an empty array.</p><pre>const regEx = /[A-Z]/g;</pre><pre>console.log(fullName.match(regEx)); <em>//[&#39;J&#39;, &#39;R&#39;]</em></pre><pre>console.log(fullName.match(&quot;Rowa&quot;));<em>//[&#39;Rowa&#39;, index: 6, input: &#39;James Rowa&#39;, groups: undefined]</em></pre><pre>const alphabet = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&quot;;</pre><pre>const regexp = /[A-E]/gi;</pre><pre>const matches = alphabet.match(regexp);</pre><pre>console.log(matches);<em>// [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]</em></pre><h3>7. repeat()</h3><p>This method returns a new string that repeats the original string a specified number of times concatenated together. The number of times the string is to be repeated must not be negative, must be less than infinity, and not overflow maximum size of string.</p><pre>console.log(1, firstName.repeat()); <em>//returns empty string</em></pre><pre>console.log(2, firstName.repeat(0)); <em>//returns empty string</em></pre><pre>console.log(3, firstName.repeat(5)); <em>//3 &#39;JamesJamesJamesJamesJames&#39;</em></pre><pre>console.log(4, firstName.repeat(-3)); <em>//Rangeerror</em></pre><h3>8. replace()</h3><p>Just like the name states, this string method returns a new string in which one, a few, or all matches of a supplied pattern are replaced by the replacing string. The replacing string can be another string or even a function that gets called every time a match occurs, while the supplied pattern can be a simple string or a regular expression.</p><p>The method takes in a pattern (string or RegExp, (any value not any of the two gets coerced into a string)) and a replacement (string or function). A string replacement simply replaces the substring matched by the pattern, while a function gets invokes for every match and the value it returns becomes the replacement string. The method returns a new string without mutating the calling string. To carry out multiple replacements (global search and replacement), a RegExp with global flag is used or the replaceAll() is used instead, otherwise the method replaces the string pattern just once. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#:~:text=Description-,String.prototype.replace(),function%20called%20for%20each%20match.">Here</a> is additional information on the replace() method.</p><pre>const lastName = &quot;Onyango&quot;;</pre><pre>const myAka = fullName.replace(/James/i, lastName);</pre><pre>console.log(myAka); <em>//Onyango Rowa</em></pre><pre>console.log(&quot;I am from East Africa&quot;.replace(&quot;East Africa&quot;, &quot;Kenya&quot;));<em>//I am from Kenya</em></pre><h3>9. search()</h3><p>The search() string is used to search for a match between a RegEx and the calling string. We may want to look for non-word or white space characters in a string, or just if there is a whitespace in a variable like the fullName above. The search() method simply calls the argument’s <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search">Symbol.search</a> method on the string. This method returns the index within a string that matches a particular RegExp.</p><pre>console.log(fullName.search(&quot;Rowa&quot;)); <em>//6</em></pre><pre>console.log(fullName.search(/[^\w]/g)); <em>//5 the only whitespace in the fullName is at 5</em></pre><pre>console.log(fullName.search(/[A-Z]/g)); <em>//0 J at index 0 is the first capital letter</em></pre><pre>console.log(fullName.search(/[[.]]/g));<em>//-1 the fullName has no full stop<br></em>console.log(fullName.search(/AmEs/i)); <em>//1</em></pre><p>In the last example, /AmEs/i is a regular expression. AmEs is a pattern (to be used in a search). i is a modifier that modifies the search to be Case-Insensitive.</p><h3>10. slice()</h3><p>The slice() method fetches and returns a part of a string without modifying the calling string. To extract and return the section of the calling string and return it as a new one, the method takes in one or two parameters, either the indexStart, or both indexStart and indexEnd. The indexStart is the first character that gets included in the new string returned while the endIndex reps the first string that gets excluded from the returned substring. When fed with a negative number as the startIndex, the index is counted from the end of the string.</p><pre>console.log(fullName.slice(5)); <em>//Rowa</em></pre><pre>console.log(fullName.slice(0, 5)); <em>//James</em></pre><pre>console.log(fullName.slice(-5)); <em>//Rowa</em></pre><pre>console.log(fullName.slice(3, -3)); <em>//es R</em></pre><pre>console.log(fullName.slice(0)); <em>//James Rowa</em></pre><pre>console.log(fullName.slice());<em>//returns empty string</em></pre><h3>11. split()</h3><p>When the split method gets called on a string and fed a pattern, it divides the string into an ordered list of substrings based on the input pattern and returns an array of the resulting substrings. The purpose of the patterns is to determine where each split occurs. The split() method can take a second optional parameter, a number, which is a non-negative integer that specifies a limit of the number of substrings to be included in the returned array. With the limit, the split() method splits the calling string on every occurrence of the pattern until a point where the substrings(now array elements) equal the limit parameter. A limit of zero returns an empty array.</p><pre>console.log(fullName.split(&quot;&quot;)); <em>//[&#39;J&#39;, &#39;a&#39;, &#39;m&#39;, &#39;e&#39;, &#39;s&#39;, &#39; &#39;, &#39;R&#39;, &#39;o&#39;, &#39;w&#39;, &#39;a&#39;]</em></pre><pre>console.log(fullName.split(&quot;&quot;, 5)); <em>//[&#39;J&#39;, &#39;a&#39;, &#39;m&#39;, &#39;e&#39;, &#39;s&#39;]</em></pre><pre>console.log(fullName.split(&quot; &quot;)); <em>//[&#39;James&#39;, &#39;Rowa&#39;]</em></pre><pre>console.log(fullName.split(&quot;&quot;, 0)); <em>//[]</em></pre><pre>console.log(</pre><pre>&quot;I, James Rowa, do swear that, I understand string methods, JavaScript&quot;.split(</pre><pre>&quot;,&quot;</pre><pre>)<em>//[&#39;I&#39;, &#39; James Rowa&#39;, &#39; do swear that&#39;, &#39; I understand string methods&#39;, &#39; JavaScript&#39;]</em></pre><pre>);</pre><h3>12. substr()</h3><p>The method acts on the calling string by taking in two parameter number values, first is the starting index (index of the first character to include), and second the number of characters to extend to. It then returns a portion of the string starting from the starting index, and extending to the number of characters specified. If the starting index is greater than or equal to the length of the calling string, the method returns an empty string, while it returns undefined if it is omitted. If the starting index is less than zero, the counting starts from the end of the string.</p><pre>console.log(firstName.substr(1, 3)); <em>//ame</em></pre><pre>console.log(firstName.substr(5, 1)); <em>//returns an empty string</em></pre><pre>console.log(firstName.substr(-1, 1)); <em>//s</em></pre><h3>13. toLowerCase()</h3><p>Simply returns the calling string value to lowercase. Since JavaScript strings are immutable, the conversion this method does not affect the string’s value</p><pre>console.log(fullName.toLowerCase()); <em>//james rowa</em></pre><h3>14. toUpperCase()</h3><p>This method simply converts and returns a string it is called on converted to uppercase, and in instances where the calling value is not a string, it converts it into a string. Just like the toLowerCase() method, this method also does not affect the value of the calling string.</p><pre>console.log(firstName.toUpperCase()); <em>//JAMES</em></pre><h3>15. trim()</h3><p>The trim() method removes (trims) unnecessary white spaces from both ends of a string thereby returning a new string without modifying the original string. If the method gets called on a string without any white spaces, the string just gets copied and a new one returned.</p><pre>const whiteSpacedStr = &quot; I have white spaces &quot;;</pre><pre>console.log(whiteSpacedStr.length);//21</pre><pre>const trimmedStr = whiteSpacedStr.trim();</pre><pre>console.log(trimmedStr.length);//19</pre><p>There are two other more specific methods that perform more specific trimming, the trimStart() method which removes whitespace from the beginning of a string while trimLeft() does the exact same thing. trimRight does the opposite.</p><h3>Conclusion</h3><p>We have gone through some of the crucial string methods that a JavaScript developer needs at the tip of their fingers. Here is the <a href="https://github.com/rowah/javascript-string-methods">Github repo</a> for the article, you can edit or add methods. If you found this article helpful kindly leave a clap and follow me. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=724b45698799" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Important JavaScript Array Methods]]></title>
            <link>https://medium.com/@jrowah/important-javascript-array-methods-d50c3479a37b?source=rss-58b16ac491fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d50c3479a37b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-array-methods]]></category>
            <dc:creator><![CDATA[James Rowa]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 13:32:21 GMT</pubDate>
            <atom:updated>2022-09-13T13:32:21.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5JSWes38UjdpAJPm7dzuQ.jpeg" /><figcaption>Let’s code some array methods!</figcaption></figure><p>One of the most common things that you are going to encounter and use as a JavaScript programmer are arrays. Arrays store a collection of multiple items under a single variable name on which a number of methods can be applied. This article outlines some of the most essential array methods that will make life easier for you as a JavaScript developer.</p><p>Below is an array on which we are going to call the various array methods on and be able to see how important they can be. <strong>NOTE that each method is called on the original accounts array below and not the accounts array modified by the preceding method(s).</strong></p><pre>const accounts = [<br>  {accountName: &quot;OptimisticPanda&quot;, noOfFollowers: 100 },<br>  {accountName: &quot;SunshineSoul&quot;, noOfFollowers: 400},<br>  {accountName: &quot;GratefulHeart&quot;, noOfFollowers: 150},<br>  {accountName: &quot;DynamicDiva&quot;, noOfFollowers: 300},<br>  {accountName: &quot;SassyStarlet&quot;, noOfFollowers: 1200},<br>  {accountName: &quot;BelieveInYou&quot;, noOfFollowers: 56000},<br>  {accountName: &quot;PeacefulPlace&quot;, noOfFollowers: 426},<br>  {accountName: &quot;Rodenta&quot;, noOfFollowers: 12301}<br>]</pre><h3>1. Filter Method</h3><p>The filter method returns a new array containing all elements of the calling/original array for which the provided filtering function returns true. If we wanted to get all accounts which have less than 500 followers, we would call the filter method on the accounts array which takes in a filtering function that filters out all the other accounts which have 500 followers and above. The filter method takes in a simple function that takes one parameter called account. All the accounts with less than 500 followers should be on the new lessThan500Followers array.</p><pre>const lessThan500Followers = accounts.filter(account =&gt; {<br>  return account.noOfFollowers &lt; 500;<br>})<br>console.log(lessThan500Followers);</pre><pre>//On the console you should see the new array below<br>//[<br>//{<br>// accountName: &#39;OptimisticPanda&#39;,<br>// noOfFollowers: 100<br>//},<br>//{<br>// accountName: &#39;SunshineSoul&#39;,<br>// noOfFollowers: 400<br>//},<br>//{<br>// accountName: &#39;GratefulHeart&#39;,<br>// noOfFollowers: 150<br>//},<br>//{<br>// accountName: &#39;DynamicDiva&#39;,<br>// noOfFollowers: 300<br>//},<br>//{<br>// accountName: &#39;PeacefulPlace&#39;,<br>// noOfFollowers: 426<br>//}<br>//]</pre><pre><em>// ]</em></pre><p>It is important to note that the filter methods does not change the original array that we filtered over and so logging accounts on the console gives the original array.</p><h3>2. Map Method</h3><p>The map method takes an array and transforms it into a new array by invoking a function on every element in the original array which leads to a slight transformation of each element of the original array. In our accounts we might want to add 10 followers to each account and so we can achieve that by calling the map method on the accounts array. We get a new array of number of followers for each account increased by 10.</p><pre>const moreFollowers = accounts.map((<em>account</em>) =&gt; {</pre><pre><em>return</em> <em>account</em>.noOfFollowers + 10;</pre><pre>});</pre><pre>console.log(moreFollowers);</pre><pre>//[110, 410, 160, 310, 1210, 56010, 436, 12311]</pre><h3>3. Reduce Method</h3><p>This is perhaps one of the most challenging array methods in JavaScript. The reduce method conducts some operation (reduction) supplied by the callback function on each array element in their order, and returns the result onto the next element. This reduction leads to a single value end result after the last element in the array is reached.</p><p>When the callback function that supplies the reducer runs for the first time on the zero-indexed array element, no return value of the previous calculation is passed. However, an initial value can be supplied which can then be used in place of the non-existent return value of the previous calculation, but if not supplied, the zero-indexed array element becomes the initial value and the reduction starts at the one-indexed array element. In many cases, 0 is always provided as an initial value where the reduce method is applied.</p><p>The reduce method is unique in that it takes in an item and a property for what we want to reduce everything into, and takes in a third parameter, the 0 initial value which acts as the starting point. In our array, we can apply the reduce method when we want to know the total number of followers that all the accounts have.</p><pre>const allFollowers = accounts.reduce(</pre><pre>(<em>previousTotal</em>, <em>currentAccount</em>) =&gt;</pre><pre><em>previousTotal</em> + <em>currentAccount</em>.noOfFollowers,</pre><pre>0</pre><pre>);</pre><pre>console.log(allFollowers);<em>// </em>70877</pre><p>The first item of the reduce method (<em>previousTotal</em>) is the return value of the previous calculation, while the second item is the actual array item, in our case, the currentAccount but then we are summing up the number of followers. On the very first iteration, the current total starts with the 0 that we passed as the second parameter. Thus on the first iteration, the method adds 0 as the previousTotal to 100, which is the number of followers of the current account (OptimisticPanda), and returns 100. On the next iteration, the previousTotal becomes 100, and the currentAccount becomes SunshineSoul with 400 followers. The final iteration returns a value that gives the total number of followers in all the accounts.</p><h3><strong>4. Find Method</strong></h3><p>The find method allows you to find the first element in an array that satisfies the provided testing function. If no appropriate element id found, the method returns undefined. We might want to find an account with a specific name such as DynamicDiva.</p><pre>const foundAcc = accounts.find((<em>account</em>) =&gt; {</pre><pre><em>return</em> <em>account</em>.accountName === “DynamicDiva”;</pre><pre>});</pre><pre>console.log(foundAcc); <em>//{accountName: ‘DynamicDiva’, noOfFollowers: 300}</em></pre><h3>5. forEach Method</h3><p>Unlike the above methods, the forEach method does not actually return anything. It works just like a for loop but takes a function instead which is called for each element in the array. Suppose we wanted to get the account names from the account objects, the forEach method would come in handy. It also takes in an item.</p><pre>accounts.forEach((<em>account</em>) =&gt; {</pre><pre>console.log(<em>account</em>.accountName);</pre><pre>});</pre><pre><em>// &#39;OptimisticPanda&#39;</em></pre><pre><em>// &#39;SunshineSoul&#39;</em></pre><pre><em>// &#39;GratefulHeart&#39;</em></pre><pre><em>// &#39;DynamicDiva&#39;</em></pre><pre><em>// &#39;SassyStarlet&#39;</em></pre><pre><em>// &#39;BelieveInYou&#39;</em></pre><pre><em>// &#39;PeacefulPlace&#39;</em></pre><pre><em>// &#39;Rodenta&#39;</em></pre><h3>8. Includes Method</h3><p>The includes methods determines if an array includes a certain value and returns either true or false depending on the availability of that element. We may want to check if our array contains a particular account if we had vary many accounts in our array. The includes method is simple and takes just a simple value</p><pre>const followers = [100, 400, 130, 300, 1200, 56000, 426, 12301];</pre><pre>console.log(followers.includes(12301));//true</pre><h3>6. Some Method</h3><p>This method tests whether at least one element in the array passes the test implemented in the testing function and return true or false. In our array, we can use the some method if we wanted to check if there are account(s) with no followers. It returns false since there is not a single account without a follower.</p><pre>const zeroFollowers = accounts.some((<em>account</em>) =&gt; {</pre><pre><em>return</em> <em>account</em>.noOfFollowers == 0;</pre><pre>});</pre><pre>console.log(zeroFollowers); <em>//false</em></pre><h3>7. Every Method</h3><p>This methods works the same as some method except that it checks if every element in the array passes the test implemented in the testing function and if they all do, it returns true. If even just one element fails to pass the test, it returns false. We might want to check if every account has100 or more followers and here the every method would come in handy. It return true since the account with the least number of followers has 100.</p><pre>console.log(</pre><pre>accounts.every((<em>account</em>) =&gt; {</pre><pre><em>return</em> <em>account</em>.noOfFollowers &gt;= 100;</pre><pre>})</pre><pre>); <em>//returns true</em></pre><h3>8. Splice Method</h3><p>The splice method deletes, inserts, and/or replaces elements in an array. Its syntax is;</p><pre>arr.splice(start[, deleteCount, element1, ..., elementN])</pre><p>Explaining the syntax; the method modifies the array starting from index represented by <em>start; </em>it then removes the number of elements represented by <em>deleteCount</em>; and then replaces them with <em>element1, …, elementN.</em></p><p>Starting with deletion, if we wanted to remove the account object at index 1 from the array named SunshineSoul, we would use the splice method and feed in the index from which to start the deletion and the number of items to delete. Thus the method removed one element starting from index 1.</p><pre>accounts.splice(1, 1);</pre><pre>console.log(accounts);</pre><p>We can also use the splice method to do element replacement in arrays. If we wanted to replace accounts at indices 1 and 2 with two new account objects, we would.</p><pre>const deletedAccounts = accounts.splice(1,2,</pre><pre>{ accountName: &quot;Tumbulu&quot;, noOfFollowers: 450 },</pre><pre>{ accountName: &quot;Bondo&quot;, noOfFollowers: 340 }</pre><pre>);</pre><pre>console.log(accounts);</pre><pre><em>// [{accountName: &#39;OptimisticPanda&#39;, noOfFollowers: 100},</em></pre><pre><em>// {accountName: &#39;Tumbulu&#39;, noOfFollowers: 450},</em></pre><pre><em>// {accountName: &#39;Bondo&#39;, noOfFollowers: 340},</em></pre><pre><em>// {accountName: &#39;DynamicDiva&#39;, noOfFollowers: 300},</em></pre><pre><em>// {accountName: &#39;SassyStarlet&#39;, noOfFollowers: 1200},</em></pre><pre><em>// {accountName: &#39;BelieveInYou&#39;, noOfFollowers: 56000},</em></pre><pre><em>// {accountName: &#39;PeacefulPlace&#39;, noOfFollowers: 426},</em></pre><pre><em>// {accountName: &#39;Rodenta&#39;, noOfFollowers: 12301}]</em></pre><p>It is important to note that the splice method returns an array of the replaced accounts.</p><pre>console.log(deletedAccounts);</pre><pre><em>//[{accountName: &#39;SunshineSoul&#39;, noOfFollowers: 400},</em></pre><pre><em>//{accountName: &#39;GratefulHeart&#39;, noOfFollowers: 150}]</em></pre><p>We can also use the splice method to add an account object to our accounts array without deleting any of the existing accounts.</p><pre>accounts.splice(3, 0, { accountName: &quot;Royman&quot;, noOfFollowers: 5000 });</pre><pre>console.log(accounts);<br>//Expected output</pre><pre><em>// [{accountName: &#39;OptimisticPanda&#39;, noOfFollowers: 100},</em></pre><pre><em>// {accountName: &#39;SunshineSoul&#39;, noOfFollowers: 400},</em></pre><pre><em>// {accountName: &#39;GratefulHeart&#39;, noOfFollowers: 150},</em></pre><pre><em>// {accountName: &#39;Royman&#39;, noOfFollowers: 5000},</em></pre><pre><em>// {accountName: &#39;DynamicDiva&#39;, noOfFollowers: 300},</em></pre><pre><em>// {accountName: &#39;SassyStarlet&#39;, noOfFollowers: 1200},</em></pre><pre><em>// {accountName: &#39;BelieveInYou&#39;, noOfFollowers: 56000},</em></pre><pre><em>// {accountName: &#39;PeacefulPlace&#39;, noOfFollowers: 426},</em></pre><pre><em>// {accountName: &#39;Rodenta&#39;, noOfFollowers: 12301}]</em></pre><h3>9.Slice Method</h3><p>Extracts a section of the calling array and returns a new array, with the original array remaining unmodified. Basically, the slice method takes an array, returns a shallow copy of the array into a new array from <em>start</em> to <em>end</em> where the <em>start</em> and <em>end</em> represent the index of items in the original array. Key point to not is that the array element in the <em>end</em> index doesn’t get included in the new array</p><pre>console.log(accounts.slice(3));</pre><pre><em>//Expected Output<br>// [</em></pre><pre><em>//   { accountName: &quot;DynamicDiva&quot;, noOfFollowers: 300 },</em></pre><pre><em>//   { accountName: &quot;SassyStarlet&quot;, noOfFollowers: 1200 },</em></pre><pre><em>//   { accountName: &quot;BelieveInYou&quot;, noOfFollowers: 56000 },</em></pre><pre><em>//   { accountName: &quot;PeacefulPlace&quot;, noOfFollowers: 426 },</em></pre><pre><em>//   { accountName: &quot;Rodenta&quot;, noOfFollowers: 12301 },</em></pre><pre><em>// ];</em></pre><pre>console.log(accounts.slice(2, 4));</pre><pre><em>// [{accountName: &#39;GratefulHeart&#39;, noOfFollowers: 150},</em></pre><pre><em>// {accountName: &#39;DynamicDiva&#39;, noOfFollowers: 300}]</em></pre><h3>Conclusion</h3><p>This article covers some of JavaScript array methods which I believe are important to master. Although the other methods not discussed here are essential to you as a JavaScript developer as well, you are less likely to need them. Be sure to check out the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">MDN Array documentation</a> for an extensive list of array methods.</p><p><em>If you found this article important, I humbly request you to leave a 👏🏿 and follow me for more articles. You can also find me on </em><a href="https://twitter.com/Jrowah"><em>Twitter</em></a><em> and </em><a href="https://github.com/rowah"><em>GitHub</em></a>, <em>where you can add more methods on the </em><a href="https://github.com/rowah/javascript-array-methods"><em>article’s Github repository</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d50c3479a37b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Model-View-Controller (MVC)]]></title>
            <link>https://medium.com/@jrowah/the-model-view-controller-mvc-ce4c9c660de5?source=rss-58b16ac491fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce4c9c660de5</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[model-view-controller]]></category>
            <dc:creator><![CDATA[James Rowa]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 17:10:51 GMT</pubDate>
            <atom:updated>2022-08-31T17:10:51.700Z</atom:updated>
            <content:encoded><![CDATA[<p>The MVC is software design pattern that organises a software application into three main logical components: the <strong>Model</strong>, the <strong>View</strong>, and the <strong>Controller</strong>, with each component handling specific development aspects of the application.</p><p>In summary, using the MVC pattern, requests such as page refreshing or form submissions by users through browsers get routed by a router to the Controller which works with the Model to carry out actions or retrieve query results depending on the user requests. The Controller communicates with the View and displays to the user while providing the required data Model. The data is retrieved by the Model from the DataBase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*2FYjq24gDSwc6VgTunjaWA.png" /></figure><p>Routes are constraints that determine the running of the Controller, ie, when the particular request specifies a particular Controller class method. In MVC, a route matches the file with the code and markup that render responses to the user through the browser. Routing makes it possible to map request handlers. The router specifies the route that then identifies the specific controller Action method that then handles the particular request.</p><p><strong>Model</strong></p><p>The Model represents an application’s state and encapsulates the business logic or operations it performs. It gets and manipulates data from the database that application users work with through selection, insertion, updating and deletion. The Model interacts with the database while communicating with the controller and passes on the data that gets transferred between the View and Controller. It enables the Controller to create and manipulate ViewModels instance which are designed to contain the data to be displayed on the View. This part of the design dictates what data an application contains.</p><p><strong>View</strong></p><p>Views define what the end user sees ie the User Interface as they present data embedded in HTML markup through templating languages such as embedded js, Mustache, and HandleBars. View communicates with the Controller and defines how the app’s data should be displayed. There should be minimum logic in Views and if any, it has to relate to content presentation.</p><p><strong>Controllers</strong></p><p>Controllers are the components responsible for handling user interactions, work with the Model to get data to and from the DataBase and select a view to render. Generally, a Controller, from its name, controls an application’s response to requests from users. The Controller receives input from View and url. They process the create, read, update and delete requests which correspond to the POST, GET, PUT, and DELETE HTTP methods.</p><p>An Object Data Modelling library called Mongoose connects MongoDB and Node.js runtime Environment. This object modelling tool provides a Schema-based solution to model apps. It manages relationships between data and translates between objects in code and their representation in MongoDB. A schema, on the other hand is a skeleton structure that reps the logical view of an entire DB by defining entities and how they relate. It is a blueprint/architecture of what data will look like in the DB</p><p><strong>Why MVC?</strong></p><p>The pattern mainly helps in achieving separation of concerns when building applications. It helps scale the complexity of applications as it makes it easier to code, debug, and run tests. An example of this is when presentation code and business logic are combined in a single object (no MVC), it often leads to errors on the business logic since modifications on the user interface logic tend to be frequent and each change must therefore require a review of the business logic.</p><p>The separation of concerns brought by the MVC design make the View and Controller dependent on the Model, which however, is independent of the two thus allowing the model to be built and tested independent of the visual presentation.</p><p>MVC also facilitates a better division of labour when an application is being worked on by a team of developers and helps new members of the development team to easily get at par with the code, making them understand code better. It also facilities debugging and organised programming.</p><p>MVC can be applied in building simple to complex full stack web applications using express and many more. Read through my simple full stack express web <a href="https://medium.com/p/ce4c9c660de">shopping list app</a> where I put MVC into practice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce4c9c660de5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>