Monthly Archives: June 2018

Destructuring

“Destructuring” does not mean “destructive”

It’s called “destructuring assignment”, because it “destructurizes” by copying items into variables. But the array itself is not modified.

It’s just a shorter way to write:

Thus, we can do a shorthand like so?

arguments object

The Arguments Object

JavaScript functions have a built-in object called the arguments object.

The argument object contains an array of the arguments used when the function was called (invoked).

This way you can simply use a function to find (for instance) the highest value in a list of numbers:

..or create a sum function

Arguments are Passed by Value

The parameters, in a function call, are the function’s arguments.

JavaScript arguments are passed by value: The function only gets to know the values, not the argument’s locations.

If a function changes an argument’s value, it does not change the parameter’s original value.

Changes to arguments are not visible (reflected) outside the function.

spread operator

ref – https://codeburst.io/javascript-the-spread-operator-a867a71668ca

The spread operator allows an expression to be expanded in places where multiple elements/variables/arguments are expected

given…normally, the middle reference in arr would reference var middle. This makes it so that its an array inside of an array. Its not what we want.

What we can do is to expand middle’s elements into arr like so:

Remember the spread operator definition you just read above? Here’s where it comes into play. As you can see, when we create the arr array and use the spread operator on the middle array, instead of just being inserted, the middle array expands. Each element in the middle array is inserted into the arr array. This means that instead of nested arrays, we are left with a simple array of numbers ranging from 1 to 6.

Copying arrays

Voila! We have a copied array. The array values in arr expanded to become individual letters which were then assigned to arr2. We can now change the arr2 array as much as we’d like with no consequences on the original arr array.

Appending Arrays

String to Array

Bonus example: Use the spread operator to simply convert a string to an array of characters

No need to use ‘call’

default parameters

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

Evaluated at runtime

The default argument gets evaluated at call time.

we can even assign functions to it:

with call, argument list, and default parameters

then we declare a function with defaults.

The 1st param a references 1st param.
We then have 2nd param b, which defaults to 5.
3rd param c copies over from 2nd param.
d param references go function
e references the ‘this’ object, whatever it is pointing.
f references the default argument list
g references the ‘this’ object, and then access its property ‘value’

We call the function like so:

using call, we provide the first object as the ‘this’ object for withDefaults function. the integer 6680 is the 1st parameter.
thus, just from this knowledge:

a will be 6680
e is the {value: ‘=^_^=’}

We then look at the 2nd param which is b = 5.
third is c = b, which means c is 5.
param 4 is d referencing the returned string of function go().
param 5 e reference the this object, which is supplied by our call function’s 1st parameter.
Hence e references {value: ‘=^_^=’}

f references the basic argument list
finally, g references the this object’s value property.


output:

a is referencing param1: 6680
b references 5
c references 5
d references function go(), which returns 😛
e = this:
{ value: ‘=^_^=’ }
f = [object Arguments]
=^_^=

Object as Hash

ref – https://medium.com/front-end-hacking/es6-map-vs-object-what-and-when-b80621932373

Object is the great choice for scenarios when we only need simple structure to store data and knew that all the keys are either strings or integers (or Symbol), because creating plain Object and accessing Object’s property with a specific key is much faster than creating a Map (literal vs constructor, direct vs get() function call).

An Object in Javascript is dictionary type of data collection — which means it also follows key-value stored concept.

Construction

In general, like in Array, do not use built-in constructor over literal in creating new object, because:

  • More typing
  • Slower performance
  • Confusion & increasing more chances for mistake

for example:

Setting key/values

You can initialize it with key/value pairs, or simply assign it via brackets.
Each key in Object — or we normally call it “property” — is also unique and associated with a single value.
In addition, Object in Javascript has built-in prototype. And don’t forget, nearly all objects in Javascript are instances of Object.

Object: keys must be in simple types (int, string, or symbol)

In Object, it follows the rule of normal dictionary. The keys MUST be simple types — either integer or string or symbols. As shown previously, strings and integers are used often. However, we can also use symbols.

Looping through the Object keys

Looping through symbols

try catch performance issues

ref –

  • http://shanghaiseagull.com/index.php/2018/06/22/try-catch/
  • http://shanghaiseagull.com/index.php/2018/06/25/throw-error/
  • https://stackoverflow.com/questions/3217294/javascript-try-catch-performance-vs-error-checking-code
  • https://stackoverflow.com/questions/1722964/when-to-use-try-catch-blocks

Programs must be written for people to read, and only incidentally for machines to execute

Always aim for readable code

The key thing to remember is: Avoid try-catch in performance-critical functions, and loops

Anywhere else they won’t do much harm. Use them wisely, use them sparingly. As a side note if you want to support older browsers they may not have try-catch.

The try-catch block is said to be expensive. However if critical performance is not an issue, using it is not necessarily a concern.

The penalty with try-catch blocks everywhere is:

  • Readability: plumbing your code with plenty of try-catch is ugly and distracting
  • inappropriate: it’s a bad idea to insert such block if your code is not subject to exception-crash. Insert it only if you expect a failure in your code.
  • the try-catch block is synchronous and is not effective when it comes to async programming. During an async request you handle both the error and success events in dedicated callbacks. No need for try-catch.

The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.

Don’t catch an exception if you’re only going to log the exception and throw it up the stack. It serves no meaning and clutters code.

Do catch an exception when you are expecting a failure in a specific part of your code, and if you have a fallback for it.

Of course you always have the case of checked exceptions which require you to use try/catch blocks, in which case you have no other choice. Even with a checked exception, make sure you log properly and handle as cleanly as possible.

Assuming undefinedfunction() is undefined, when the browser runs it, no errors will be shown. The syntax for try/catch/finally is a try clause followed by either a catch or finally clause (at least one or both of them). The catch clause if defined traps any errors that has occurred from try, and is indirectly passed the error object that contains additional info about the error. Lets see a slightly more complex example now:

Click on the above button, and notice how only “An Error has occurred” alert pops up, but not “I guess you do exist”. This tells us that when try encounters an error, it immediately skips any remaining code inside it and goes straight to catch. The default error message is obviously suppressed, though you can still retrieve this information by accessing the Error object that gets indirectly passed into catch.

throw error

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won’t be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.

You can keep throwing the same exception. Once its caught, in your catch block, just do another try/catch so you can throw again.

Or you can wrap it inside of a try catch. So that whatever is thrown, the outside will catch it.

You’ll get it an error if you run function a, there is nothing to catch it. What we can do is to put function a inside of another try catch like so:

output:

caught 344 globally

Custom Errors

we declare a custom error function like so:

We will create an instantiation of this function and throw it in another function called getMonthName.
We basically give it a numeric to indicate a month. It uses that number to get the string of the month. Then we
simply return the string.

However, numerically, a month is only 1-12. If we give it say, 15, then in the array, it would be undefined.
In that case, we throw instantiation of our function like so:

As long as the throw is within a try/catch, then it will be valid.

Here is the function that try and catches the block of code. As you can see, once the user puts a erroneous parameter, we can catch it if the array returns undefined.

The reason why our throw will be caught is because our function is wrapped by a try catch.

try catch

ref – https://stackoverflow.com/questions/7148019/when-should-you-use-try-catch-in-javascript

When a single, unconditional catch clause is used, the catch block is entered when any exception is thrown. For example, when the exception occurs in the following code, control transfers to the catch clause.

The catch block specifies an identifier (e in the example above) that holds the value specified by the throw statement. The catch block is unique in that JavaScript creates this identifier when the catch block is entered and it adds it to the current scope; the identifier lasts only for the duration of the catch block; after the catch block finishes executing, the identifier is no longer available.

finally

Note that the finally clause executes regardless of whether an exception is thrown. Also, if an exception is thrown, the statements in the finally clause execute even if no catch clause handles the exception.

You can use the finally clause to make your script fail gracefully when an exception occurs; for example, to do general cleanup, you may need to release a resource that your script has tied up.

General situations

try…catch blocks are generally encourages to be used less, and this doesn’t depend on the language you use.

The main reason for this is the cost of catch blocks. Also another reason is that, when you wrap many statements with a single try…catch block, in catch block you can’t be sure what was exactly the main problem.

It’s better to use techniques like validation or if…else blocks to reduce the probability of an exception (error) to happen. For example, when you want to work with a number which is taken from user, instead of using try…catch, you can use:

deeply nested objects where a null can pop up at any level

to perform this “get” with 100% safety one would have to write a bit of verbose code:

Now imagine the variable names are realistic and longer and you quickly get a very ugly code if statement.

I tend to use try/catch/finally to simplify this when I don’t care about any “else” scenarios and just want the object or not:

Hash Table (Linear Probing)

ref – https://github.com/redmacdev1988/LinearProbeHashTable
https://stackoverflow.com/questions/9124331/meaning-of-open-hashing-and-closed-hashing

Linear Probing is an Open Addressing scheme for hash tables.

The “open” in “open addressing” tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what’s already in the hash table.

The “closed” in “closed hashing” refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table’s internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why “closed hashing” and “open addressing” are synonyms.

Best case – O(1).
For insertion, it hashes to an empty element. We insert. done.
For search, it hashes to its initial location. We do a check. Keys match. done.
Deletion – Searches for the element with the key. We find it. We remove it. The next element is empty so we’re done.

Worst case – all are O(n), because the worst possible case scenario is that we have to iterate the whole array after the initial collision.

Insertion

Insertion for linear probe deals with 2 steps:

1) hash to a location. If the location is empty, done.
2) If the location is occupied, we probe for an empty space.

Probe involves going step by step down the cells and trying to find an empty cell. Once found, we place the object there.
Note that we do not circle around back to the beginning of the array. If no empty cells are to be found, we return -1. Other alternatives can be to grow the array and try inserting again.

Retrieving the object

Searching for a cell with a certain key involves starting at the hashed index:

1) If the keys match, then return the cell. If no match, keep going forward (probe) and looking for a match on our key.
2) If an empty cell is found, the key is not in the table. If the key did exist, it would be placed in the empty cell first, and not have gone any further in the later cells. This is because during insertion, when a value is hashed and there is a collision, it would naturally probe until it finds an empty spot to put its object. Thus, when searching, hitting an empty spot means its the end of the line for a particular item that was hashed to a previous location.

Deleting an Object

Deleting an item is the same as searching. When we have successfully found the cell it delete, we:

1) remove the cell so the array element references null
2) Here’s the important part. Once the element was is removed in 1), we need to find a replacement down the line. The reason why we need to find a replacement is shown below.

Say we want to insert key “job”. It gets hashed to index 6, then we move it to the next empty space, which is index 9.

The next operation is that we want to remove key “last name”. So last name gets hashed to index 6. We go down the array until we find “last name” at index 8. We remove it.

Now, say we want to search for key “job”. It would get hashed to index 6. Then it would keep going and then it would hit index 8 on an empty cell. It would stop and say key “job” does not exist. However, clearly, job exists down the line at index 9.

Solution on what to do for the empty space after deletion

When deleting, we remove the cell, then:

1) then go down the list to find a replacement for this empty cell
2) The replacement must have a key equal or smaller than the recently deleted item.

This is because all items are inserted on or after its initial hashed index. Thus, we can replace the empty cell with hashed index that is smaller because the search is coming from the left.

But why? take a look at an example:

Sa we want to delete key “last”, which was initially hashed to index 6, and probed to index 7. Now, from the previous example, we know we can’t just let it go like this.

We must go down the line and find a replacement. The notion is that we must find a replacement that has key <= our key. But what if we dont' do this? What will happen? Say we simply get the next available replacement, which in our case, is key "name" (initially indexed to 8). So as you can see, say we bring key "name" over to index 7. Then, we make a search for key "name". Its initial hash index would be 8. And it wouldn't find anything there. If data does get placed there, it wouldn't be key "name" that we're looking for. Let's see what would happen if we iterated the array for a cell that has a key <= to our key. Picking an element with hash <= removed element's hash

So after removing key “last”, we can’t just get any element to replace it. We must find an element with a hash <= our hash. Since we've removed "last" with key of 6, we then iterate the array to find that element. We go down the list, name has hash 8, nope. job has hash 8. nope. age has has 6. Perfect! so we move the element with key "age" and hash 6 to index 7. Don't forget that we must do this continuously until we hit an empty slot or the end of the array. Now, when you try to search for "age", it will hash you to index 6, which you collide with key first. Then you probe. At index 7, we have found the element with key "age". done!

Encapsulation

Functions that satisfy Use Case scenarios should be public.
Any other functions that are used by the public functions are to be private.

Thus, insertion, retrieving index, deleting, and printing should all be public.

Thus, I the public functions are:

insertAndCheckLoad
retrieveIndex
delete
print

All the other functions are private:

hash
loadFactor
probeAndInsert
insert
growArray

One issue to note is that the private functions’s this belong to global (or “undefined” if using strict). You need to connect its ‘this’ context to our object. Some standard ways are to use call/apply. But you can also define a private variable _self, where it references the this context.

Once declared, you can freely use it any private functions.
In our loadFactor example, we use scope to access private _self, which references the correct this context.

Iterating Array elements

ref – https://stackoverflow.com/questions/5349425/whats-the-fastest-way-to-loop-through-an-array-in-javascript

given array

filter

forEach

map

warning: map is for generating a new array, we manipulate each element, and the function generates a new array with those new changes.
Its purpose is not really for iterating an array. For completeness, it is included.

for loop

while loop