Thursday, December 27, 2018

Observer Pattern

I have been sitting on this blog for a while. I finished the chapter a while ago, but not sure exactly why I wasn't getting to writing the blog post. At one time I had a few blogs written so I could just post, then I got sick or something and fell behind. I am obviously not as prepared as I was at that time. I am not going to make any promises because, when it comes to blogging, I don't usually keep the promise to write once time a week. At this point I am once a month. Let's put it out there. I will write one blog a month.

Let's start (and finish) December with Observer Pattern. The thought behind the Observer Pattern is pretty simple, objects subscribe to events and when that event happens the object will get notified. It is very similar to a newspaper model (except we hope the Observer Pattern doesn't get the same fate of newspapers). The object is an observer, or subscriber, to the subject, or publisher. Each morning a paper gets published and sent to everyone that subscribes to it. One can unsubscribe from the newspaper at anytime in order to stop receiving the papers, or new people can subscribe at any time.

Each object should implement an interface subject and all observers should implement an observer interface. The concrete observer will register with a concrete subject to receive updates.The concrete subject will contain methods to add or remove subscribers.

When the observer is subscribed to the subject anytime a change in the subject happens the observer will be notified. If the observer gets tired of receiving the notifications it can unsubscribe. This pattern allows for loose coupling:

  • The only thing the subject knows about an observer is that it implements a certain interface
  • We can add new observers at any time
  • We never need to modify the subject to add new types of observers
  • We can reuse subjects or observers independently of each other
  • Changes to either the subject or an observer will not affect the other

Loosely coupling allows for a pretty flexible design and will minimize the number of changes that we have to make if any changes need to make changes.

Different frameworks already have ways to do the Observer Pattern, in Java there is a built-in observable class in the java.util package. And C# you can use delegates and events. It will take a little research to find the correct way to implement the Observer Pattern in whatever you are using, or you can implement your own (probably not the most effective way to do it) as I did in the link below:

Link to my example

Alright, next up? Good question, but I want to get Google Analytics or some sort of analytics on jorgfam.com. We will see what January brings.


"Maybe Christmas, the Grinch thought, doesn't come from a store." - Dr. Seuss

Wednesday, April 18, 2018

Strategy Pattern

I have been reading about design patterns. I realize that I often use them, but could not tell you what the are called or why the are good/bad. I decided to pick up a book, Head First Design Patterns, and look for other resources online as I read. I found a nice Pluralsight video that has many design patters included in the video called Design Patterns Library.

The first pattern in the book is the Strategy Pattern. This allows you to use a family of algorithms and the one that will be used is decided at run time. Each algorithm is encapsulated into the family and makes them interchangeable. This makes it beneficial when you have multiple classes that need an algorithm of the same type, such a speaking behavior, but not all classes implement the behavior in the same way.

Most animals have a form of speaking, dogs bark, cats meow, etc. So, if you take a class of Animal which contains a method for speaking then each class that extends animal will be able to speak. Now you have an issue, you will have to override the speak method for each class that inherits from Animal. That means a lot of extra code, and if the speak behavior ever needs to change you may miss changing one.

This is where the Strategy Pattern can come in handy. Now you have an interface for speaking Animal strategy, say ISpeaking. Then you have classes that extends the interface for different types of animal: dog, cat, etc. These classes will look something like:

public interface IAnimalType
{
   String Speak();
// other things animals need/do
}

public class Dog: IAnimalType
{
public String Speak() 
{
return "I am a dog, here me bark...woof!";
}
}

public class Cat: IAnimalType
{
public String Speak() 
{
  return "I am a cat, here me meow...if you can find me!";
}
}

We can then pull the strategies in an Animal context with code similar to:

public class Animal
{
IAnimalType iAnimalType;
// Other interfaces needed to make a true animal

public Animal(IAnimalType iAnimalType)
{
this.iAnimalType= iAnimalType;
// Your other animal interfaces go here
}

public void Speak()
{
Console.WriteLine(this.iAnimalType.Speak();
}
}

We can go to a employee now and return different request to the HRContext by selecting a strategy.

class Program
{
static void Main(string[] args)
{
Animal dog = new Animal(new DogType());
Animal cat = new Animal(new CatType());

Console.WriteLine("Here is a Dog");
dog.Speak();

Console.WriteLine("Here is a Cat");
cat.Speak();
}
}
If we were to run this program we would get out what each animal says. If we ever need to change what one type of animals speak behavior is, we just change it in one spot and don't need to worry about forgetting one.

Using this pattern also allows us to use an Open/Close principle, which is that the classes are open for extension but closed for modifications. We can add any type of animal and will not need to update our iAnimalType or Animal classes.


"You can't expect to hit the jackpot if you don't put a few nickels in the machine." - Flip Wilson

Wednesday, April 11, 2018

Sorting Objects in arrays

I finished a challenge on Free Code Camp called Inventory Update. The challenge asked you to update the first array (inventory) with either the array 2 (delivery) items if they don't exist in the inventory or update the inventory number if the item already exists in the inventory.

The arrays weren't objects with names, they came across with an integer and text. For example, my first item in array one was [10, "Bowling Ball"]. I probably could have converted each item in the array to an inventory item so then I would have [quantity: 10, name: "Bowling Ball"]. But with the all you can do with arrays I didn't find that necessary (although if this were a program for someone, it would have been beneficial to make the array into a more usable format instead of using array1[i][0].

Adding new items and updating the value of an item already in inventory seemed easy. I created a function to see if the array contained the inventory item and updated the amount. If it didn't contain it, push in the new array item.

function contains(obj) {
for (var i = 0; i < arr1.length; i++) {
if (arr1[i][1] === obj[1]) {
arr1[i][0] += obj[0];
return true;
}
}
arr1.push(obj);
return false;
}

Now came the more tricky part. The challenge asked you to alphabetize the items in the inventory. You know, make it easy to find an item in the list. I tried arr1.sort() but this seemed to just sort off the first item in the object of the array which was the quantity in the inventory. Great if I know the quantity of whatever I was looking up, but doesn't really make sense.

While reading, I found that you can create a function to sort your items in the array. This allows you to write a function to alphabetize based on the second member of my object, or the name of my inventory item.

I looked further and found a better way that didn't require me to write a function. Using String.prototype.localeCompare(). This compares the strings you have and returns a number that indicates whether the reference string comes before, after, or is the same as the other string provided. It then will sort the items for you.

This will allow for some options as well, such as case sensitivity, numeric, ignoring punctuation and more. It made the sorting pretty easy and able to use one line of code:

arr1.sort((a, b) => a[1].localeCompare(b[1]));

(if I had made each item in the array into an inventory object it would have been a.name and b.name instead of a[1] and b[1]).

I could see localeCompare coming in handy later in life.
"I have noticed that nothing I never said ever did me any harm." - Calvin Coolidge

Wednesday, April 4, 2018

Z-Index Values

Developing for different browsers can be difficult. Each browser can have it's own set of rules and coding for each browser can sure be difficult. For example when you use Flexbox you have to remember to add CSS display lines to make sure each browser will display correctly.

Recently, I was working on an informational window that will track with the question mark button. I make the window be positioned where it needed to be we ended up using NGX-Popper. Works great! You can resize the browser and the pop-up moves exactly where it needs to follow the button you pushed.

I checked how it looked in Chrome and everything was working great after adding a line in the CSS file:

.inside-popper {
z-index: 999;
}

I selected 999 just because it is a high number with the hope that a higher z-index would not be selected for another element. Looks great...until I pull it up in Internet Explorer.

When I opened this up in internet explorer, the pop-up was not the item at the front. Some elements of the pop-up were showing correctly but it seemed the background was clear and was allowing the elements behind to come to the front.

Here is a shot IE left and Chrome on the right:

I had the z-index in the CSS file but it wasn't recognizing it in IE, or so it appeared. After doing some research I found that it looks like IE generates a new stacking context for elements that are positioned. This means the z-index will have a value of 0. Z-index won't work as expected.

The work around I found was to wrap the popup in another div that had a class with a higher z-index then my pop-up:

.popper-wrap {
position: relative;
z-index: 1000;
}

.inside-popper {
z-index: 999;
}

Now IE looks the same as Chrome. Just another one of those things to watch out for when looking at the different browsers.


Wednesday, March 28, 2018

Javascript Variables

In C#, a method required you to declare the number of arguments and each arguments data type.If you declare a method requires an argument your code will not compile unless the argument is given each time the method is called. JavaScript works a little different.

JavaScript does not require you to specify the data types for each argument. It also does not perform any type of check on the arguments when the function is called. You can pass multiple arguments, or no arguments. If you declare an argument and the function receives nothing JavaScript will assume undefined for the missing arguments.

FreeCodeCamp had an algorithm where arguments were sent in different ways. For example, addTogether(2, 3) would return 5, just the sum of the two arguments passed.

 if(args.length == 2){
    if(typeof(args[0]) !== 'number' || typeof(args[1]) !=='number' ){
      return undefined;
      }
    return args[0]+args[1];
   }

But, what if you received something like addTogether(2)(3)? This confused me (and still kind of does), two sets of arguments? How do you deal with that?

I did some reading and found that it is a valid call to a function. Now I needed to figure out how to access that second variable.

It turns out that while looking at the first variable you can create another function that will look at the second variable.

if(args.length == 1){
     firstSet= args[0];
     
    if(typeof firstSet!=='number'){
        return undefined;
      }
   
    else{
       return function(secondSet){
         if(typeof secondSet !=='number'){
           return undefined;
           }
         else
            return firstSet+secondSet;
          };
      }
    }

Good to know, I'm just wondering when I will use this in real life...why would you send two sets of variables instead of just one set or an array?


"Sooner or later, those who win are those who think they can." - Paul Tournier


Wednesday, March 21, 2018

Smallest Common Multiple - using Euclid's method

I spent some time trying to figure out how I was going to solve the smallest common multiple. There are multiple ways to find this number. You can write down all the multiples and just look, you can use a grid/ladder method, prime factorization, or Euclid's method (the method I selected). If you want to see each method you can go here and see the how to accomplish through the different methods.

I decided to try and use Euclid's method. Math is used to find the greatest common divisor which is then used to find the least common multiple. Euclid's method requires you to perform the same calculation multiple times until you have a remainder of zero. You could do a while statement that looks at the remainder and stops when the remainder is zero. I also looked at a different way to do this, using recursion.

I learned about recursion a while back and figured I would give it a try here. I had a definite stopping point and needed to run the same calculations over until I got a certain number. It took me a few tries at getting the recursion to work (knowing what to put where), but I eventually landed on the below code:

function euclid(high, low) {
if(low === 0) {
return high;
} else {
return euclid(low, high%low);
}
}

I call the function and pass it the first number in an array as the high number and the second number as the low number. It then goes into the function to see that low is not at zero so it calls itself with the low number as high and the remainder of high divided by low (you use modulus to return only the remainder as the new low number. Once the modulus returns a zero, return the high number.

Euclid's method then takes the product of the first original two numbers and divides it by the number returned from our Euclid function. This will give you the smallest common multiple for the two original numbers.


"Laziness may appear attractive, but work gives satisfaction." - Anne Frank

Friday, March 16, 2018

Key Value Pair Statements - Better for the eyes, but better performance?

There have been two challenges on Free Code Camp now that I went down the road of using if statements. It started getting ugly with all those if and else if statements. You could use a case statement for each of the if statements, the case statement could possibly be easier to read and possibly have a faster performance.

Below is an example for possible DNA strings:

function pairElement(str) {
var myArray = str.split('');
var returnArray = [];
for (st in str) {
if(myArray[st] == 'G') {
returnArray.push([myArray[st], 'C']);
}
else if(myArray[st] == 'C') {
returnArray.push([myArray[st], 'G']);
}
else if(myArray[st] == 'A') {
returnArray.push([myArray[st], 'T']);
}
else {
returnArray.push([myArray[st], 'A']);
}
}

But then I got thinking, what if there were a dictionary or map that would allow someone to look up the index and see what the value output is for the item. I believe I had seen something like that before so I started searching. Turns out a map is exactly what I needed.

This technique allows me to create a map, or a key value pair, that will let me look up the value I am looking up and see it's matching string. Your first key value set G: 'C' will look up anytime your key is G it will output C.

By splitting the input string by their characters, one you are then able to use that item as the lookup for your key and return the value you need.

function pairElement(str) {
  var pairMap = {G:'C', C:'G', A:'T', T:'A'};
  var myArray = str.split('');
  
  for(var st in str) {
    myArray[st] = [myArray[st], pairMap[myArray[st]]];
  }
  
  
  return myArray;
}

The code is much easier to read and I am guessing it will have better performance as it doesn't have to check each if/else if statements.

"Nothing is work unless you'd rather be doing something else." - George Halas

Wednesday, March 14, 2018

FreeCodeCamp intermediate algorithms

I recently started FreeCodeCamp. Okay, not recently. I have been taking my time completing the challenges and tasks, but it has been pretty good. I enjoy learning the JavaScript and I am hoping I begin understanding everything more. I will be honest, I have been going slow because I am coding all day at work using Angular. Angular is great and very challenging, so why do I continue doing FreeCodeCamp?

Perhaps I feel that it will give me a foundation on the background of Angular, after all Angular uses JavaScript, right? Maybe it will help with debugging? Plus, I started FreeCodeCamp before I got hired to my team that uses Angular, and I'm not a quitter. I am to the Intermediate Algorithm Scripting and, as always, I am finding many different ways to complete the tasks they as you to do. I know that I am not the most efficient coder and there are probably much better ways to code the tasks.

I would like to go back and look at all of the tasks I have already done to see if there is something I could do better, but who knows when/if I will find time to do it. But let's start on the challenge called "Diff Two Arrays". The task seems easy enough, compare to arrays and return a new array that only contains objects that are in just one of the original arrays.

For example
arr1: [1,3,4,5]
arr2: [1,2.5,6]

My call to diffArray should return
return: [2,4,6]

My first time around I used a for statement to check each object in array1 to see if array2 included that object. Then I did the same for array2. Not the most efficient way, I know, but it worked and it was my original thought (I usually try to do the task without using the hints to see if I am able to complete the task on my own free will).

function diffArray(arr1, arr2) {
  
var newArr = [];

for(var i = 0; i < arr1.length; i++) {
   if (!arr2.includes(arr1[i])) {
     newArr.push(arr1[i]);
   }
}
  
  for(var t = 0; t < arr2.length; t++) {
   if (!arr1.includes(arr2[t])) {
     newArr.push(arr2[t]);
   }
  }
 return newArr;
}


It get's the job done. I know that I use arrow functions at work to pull data from a database, so I thought why wouldn't that work here? FreeCodeCamp mentions that you can use Array.prototype.filter() so I went to explore this in the JavaScript context. I'm going to be honest, it took me a bit to figure out how to use arr1.filter and .concat(arr2.filter). But in the end the code is much cleaner. (although it was unnerving when the FreeCodeCamp gave me a warning: " 'arrow function syntax (=>)' is only available in ES6 (use 'esversion: 6')"


function diffArray(arr1, arr2) {
  
    return arr1
      .filter(ai => !arr2.includes(ai))
      .concat(
        arr2.filter(ai => !arr1.includes(ai))
      );
}

A much simpler solution. The filter takes from each array and will remove any object that is included in the second array. Then you use concat to add the filter from arr1 to the filter from arr2.

Sometimes our first response will get it working but sometimes we need to look a bit to find a better solution.

I will post some more of these, I have plenty of examples.


"Well done is better than well said." - Benjamin Franklin