Tag: javascript

CRUD: My New App, Check Yo Self

I have taken a bit of a break from the coding/learning thing as I suffer from a bit of depression every now and again, outside of the usual. It’s a woman’s thing, as they say.

So while I was a bit down and cantankerous I took a break to tweak a few of my sites and read some documentation. After the bout of depression subsided, I dove into SQL.

Create, Read, Update, Delete: CRUD

I asked around in the Code Newbie Slack and asked my buddy Alex if I could use localStorage to store the markdown documents.

Let me backtrack.

When I was designing the app, I got the idea of having the markdown documents collect on the side of the app, sort of like the design template I was using. I knew I’d need to store those documents and really didn’t want to dive into databases.

I thought about using localStorage. Alex told me that localStorage has a capacity limit. I really don’t know how many texts someone would store and come back to, and while text files are minuscule, I don’t want to risk it.

I could go the I Need a Resume route and use setSessionCookie which would require less overhead. But if the user clears their cookies, all their texts would be wiped out.

I still plan to use setSessionCookie but I am not sure how I am going to work it in with storing the texts in the database.

CRUD is a SQL thing. 1.

ORMs and JavaScript May Save Me, Big Time

While learning SQL at Treehouse, Andrew Chalkley, the teacher, explained ORMs, or Object Relational Mapping software that helps you interface with a database in different languages. For instance, ActiveRecord for Ruby and Hibernate for Java.I was having a hard time understanding how to store the texts the users input, store the texts, and retrieve the texts up until that point in the course. Everything we did in the course was hard coded and I definitely understood I could not do that. ORMs to the rescue. Searched for an ORM for JavaScript and there are many, either through npm or other means, there are plenty. Still researching. Since I am using Postgres on Heroku, it needs to play nice with it and I found one called sequelize.js that looks like it will do the trick:


var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password');

var User = sequelize.define('user', {
  username: Sequelize.STRING,
  birthday: Sequelize.DATE
});

sequelize.sync().then(function() {
  return User.create({
    username: 'janedoe',
    birthday: new Date(1980, 6, 20)
  });
}).then(function(jane) {
  console.log(jane.get({
    plain: true
  }));
});

This snippet seems quite easy to grasp and will make interfacing with Heroku’s Postgres addon even easier. 2.

Coding Again

I plan on scanning more docs and getting the HTML up and going. I felt overwhelmed with the amount of stuff I needed to code. This is one area that hinders me still: not breaking big projects up into little pieces. I decided I have been at this enough that I should actually take Russ’s 3 and break that shit down. I fired up Drafts app on my iPhone and wrote down every task I needed and wanted to complete. Then I shifted those over to OmniFocus and Taskpaper. There are more tasks to add but I feel a sense of relief knowing that the ideas are down, and that I should work on one small bit of code at a time.

Thoughts?

I never know how to end these things. Let me know what you’re hacking on in the comments. Or not. It’s all good. ????


  1. Create: INSERT INTO, Read:, SELECT * FROM, Update: UPDATE SET, and, Delete: DELETE FROM. So that’s why they call database apps that are simple CRUD apps, which I understand finally. 
  2. Check out sequelize.js 
  3. Code Newbie field general, 1000XP 

Concise, Modular JavaScript

Working with JavaScript again at Treehouse, I went over the Arrow Syntax again1.

Before it really wasn’t making much sense. I mean, I thought I had it down, but really, it was too fast and too complicated for me at the time. I wanted to learn ES2015 and write, clean, concise, modular javascript.

So What’s Different?

I actually rewatched the videos with Andrew Chalkley this time2.

Take a look at this code:

Here we are taking no arguments passed to the function sayName()3. With arrow functions, we can write modular, clean code4. We can get rid of the function keyword and replace it with =>. Pretty nifty, eh?

Single Argument Functions

Take a look at this code:

When we have a single argument passed to a function, much like the no arguments function, we replace the function keyword with an =>. But we can also remove the curly brackets, the parens, and the return statement.5

This is getting pretty awesome.

Multiple Argument Functions

Take another gander at this gist:

Here, we can do pretty much the same thing as in the single argument function, only we need to keep the parens. Still, you can get rid of the curly braces, and the one line of code in the block.

It’s Really All The Same

Check out this gist:

It’s just a cleaner, more modular way to write code. I hear you can write modular JavaScript with Promises but I am not there yet.

Enrolled in Coursera Course

I am doing their Java Data Structures and Algorithms course. They waived the tuition and so I am starting soon. The capstone is what I am really looking forward to. I need to put in the work: 4-6 hours a week. Not too bad.

Thoughts?

Have anything to add? Leave me a comment. 🙂


  1. I called them lambda functions in this post. I don’t think they’re the same, however. 
  2. I actually rewatched them a couple times and downloaded the completed workspace. 
  3. Learning ES2015 and so we are now using const
  4. Much to the rejoicing of Uncle Bob Martin
  5. As stated in the comment, you can only do this when there is one line of code in the code block and one argument. 

Bonfire Tears (Free Code Camp Edition)

\"Crying\"

“Laughter and tears are both responses to frustration and exhaustion. I myself prefer to laugh, since there is less cleaning do to do afterward.” ― Kurt Vonnegut

There comes a point in every new programmers life when they hit a barrier, a wall, a threshold of understanding or non-understanding of the material at hand.

I hit that threshold yesterday.

And the day before it. It was a solution so simple; I had the right idea several times. I got explained to and encouraged, and guided and it was like their words were bouncing off my skull instead of being absorbed into my grey matter. The question was:

Check if a string (first argument) ends with the given target string (second argument).

Remember to use Read-Search-Ask if you get stuck. Write your own code.

Here are some helpful links:

String.substr()

The given code:

function end(str, target) {
 // "Never give up and good luck will find you."
 // -- Falcor
 return str;
}




end("Bastian", "n");

What the Hell Substrings?

\"headdesk\"

You’ve done it before and you can do it now. See the positive possibilities. Redirect the substantial energy of your frustration and turn it into positive, effective, unstoppable determination. –Ralph Marston

I knew that, since we had lengths of different strings. The tests proved that. So I kept hardcoding for one particular string. I couldn’t get past that. How do I code this thing for different string lengths? How do you get the length of a string? .length. Right? YES. But how. Where do I put the .length? I had this code:

function end(str, target) {
 //"Never give up and good luck will find you."
 // -- Falcor




//dees [8:42 PM]
//\'abcdefghijklmn\'.substr(0, 3) // \'abc\'
//"grab 3 characters starting with the character at address number 0"
​
 var isEqual = str.substr(6, 1) === target.substr(0, 1);
 return isEqual;




}
​
end("Bastian", "n");

I found out in Free Code Camp’s Gitter chat that you can get to the end of a string with a negative number; no need to keep popping off all those letters before the “n” on Bastian. But I continued to hard code for “Bastian” and “n”. I needed a broader approach.

I tried:

function end(str, target) {

​
 var isEqual = str.substr(-1) === target.substr(-1);
 return isEqual;




}
​
end("Bastian", "n");

But I wasn’t really making any progress. All but one of the tests were passing, and I wasn’t really utilizing .length to have a basic variance of string lengths. So I did this:

function end(str, target) {

 var n = target.length;
 var z = str.length;
 var isEqual = str.substr(-1) === target.substr(-1);
 return isEqual;

}
​
end("Bastian", "n");

Same result. I knew I needed to have .length; up there. But where to go after that?

Aha!

\"Aha\"

Finally, I had to be guided to the answer. The woman was in Britain and I am pretty sure I was keeping her awake. So we came up with this solution:

function end(str, target) {
 // "Never give up and good luck will find you."
 // -- Falcor

 var length = target.length;
 var isEqual = target === str.substr(-length);
 return isEqual;
}

end("Bastian", "n");

var length = target.length; gets the length of any target string and assigns it to the length variable.
var isEqual = target === str.substr(-length); compares the target string with the original string, subtracting the last characters of the length variable, starting with the end of the string.

I hope I explained that right. I understand it. It takes a bit to look at and understand but when we came to that solution, I felt like a complete idiot.

I cried. I literally did. Part of that is just me already being emotional. The other part is me not wanting to put my fist through my MacBook Pro screen. Strings are characters. Not words. And I was totally getting stuck on that.

Bonfire tears indeed.

Iterating Over an Array in Java and JavaScript

\"mac\"

I have learned that while Java and JavaScript are different, they share similarities. Someone in the Code Newbie Slack informed me of the history of JavaScript and how the creators had borrowed some functionality from Java. That’s for another post on another blog.

But while I was reading my textbook chapter on arrays, I noticed that you can iterate through an array in Java much like you can in JavaScript.

Arrays in Java are initialized completely differently as you must specify a data type and the slots you allocate in the array cannot be changed, as such, it is immutable. Here is an example of an array in Java:

int[] myArray;
myArray = new int[10];

This declares the array then initializes it with 10 int spots.

An array in JavaScript looks like this:

var myArray = ["Jerri", 69, "Tiffany", 37, "John", 39];

[1]

How Interating Through Arrays in Java and JavaScript Are Similar

\"they_all_look_the_same\"

So, I first got a taste of iterating through an array in JavaScript while working the Bonfires at Free Code Camp, which use algorithms to help you better understand the ins and outs of the language. One of the ways you can iterate through an array in JavaScript is by a for loop and a .length method depending on what you need. Here is the syntax of an algorithm I wrote in order to find out if a word was a palindrome or not:

function palindrome(str) {
 str = str.toLowerCase().replace(/[W_]/g, "");
 for(var i = 0, len = str.length - 1; i < len/2; i++) {
 if(str[i] !== str[len-i]) {
 return false;
 }
 }
 return true;
}




palindrome("eye");

Breaking It Down

The first part of this algorithm is turning all the letters in the string to lowercase and then using regex to get rid of capital letters, spaces, and punctuation[2].

The next part checks each index of the array to see if it is the same later, going inwards until it reached half the length of the array. If they are the same letter, then it’s a palindrome and will return true.

Same with Java…in a Way

The for loop in a Java array iteration looks the same when you just break it down into the method body. For instance:

public static void showArray(int|) array)
{
 for (int i = 0; i < array.length; i++)
 System.out.print(array(i] + " ");
}

Here, when the showValue method is called, an element of the array is passed to the method. It will loop through and print out each value of the elements of the array. Here we are printing it out. In the JavaScript example, we were cycling through the array to test for similarities.

The parallel? You can cycle through, and get elements/indeces of arrays with a for loop.


  1. You need to have the same data type in a Java array. If you look at the JavaScript array, I have number data types and strings. In the Java example I have 10 ints, which are numbers up to 231–1. Can’t mix data types in Java arrays.  ↩
  2. I used regex because there was a test that had to be run that included numbers and odd punctuation that had to return false.  ↩

Day 10: AJAX

\"Ajax\"

So a few days ago, I started the AJAX track at Treehouse. So with AJAX, all sorts of cool things happen, like a Google Maps, Gmail, etc, where you can load new content without reloading the page. So when you open up a map in Google Maps and scroll to another part of the map and it stays on the same page but in a different spot, you know what that is? That’s AJAX. BOOM.

So currently learning about things like XMLHttpRequest or xhr, .readystate, .onreadystatechange, and other event listeners, as well GET, POST, and JSON and error codes like 404 or 401, and the success code of 200.

Just getting into the meat of the course so I’ll keep you updated.

Day 9: Finishing Intermediate JavaScript on Treehouse Plus: New Contributor

\"DOM\"

Traversing the DOM

So I learned more about traversing the DOM with JavaScript instead of the sugary jQuery library which makes me feel great. I like jQuery and all, but knowing how to code something in pure JavaScript is something I think every new developer needs to learn and learn before learning any libraries or learning concurrently with JavaScript, like Treehouse does with it’s jQuery and JavaScript courses.

One of my favorite things about this was instead of having to use the

onclick();

event handler to traverse a certain part of the DOM (when something is clicked) you could listen for any type of click events with

addEventListener

to listen for a click on an element specified as the argument to the method. For instance here:

addButton.onclick = addTask;
//Set the click handler to the addTask function
addButton.addEventListener(&quot;click&quot;, addTask);
addButton.addEventListener(&quot;click&quot;, ajaxRequest);

This is much faster and easier than traversiing each element with the

onclick();

method.

Welcome Aboard Nick Lash as a New Contributor to the Blog

Nick and I connected on LinkedIn and, impressed with my social media and blogging output, reached out to me to collaborate on the blog and my podcast which you can find here. I found a place for him to write here and he will be a co-host on my weekly show which hasn’t been weekly in a minute. My fault totally. But that changes with Nick on board.

Thanks Nick and I hope you get something out of it. I hope my readers enjoy his posts as well. You can find Nick on Twitter.