About the Author:

Decorating (your Javascript) for Fun and Profit

February 20th, 2017

Sometimes you need to get “meta”. What if you could tell a variable that any time it changes, it should automatically report that change to a log file, without you having to write code to do it? What about identifying a function should be called by a web server whenever a particular URL pattern is matched? Or maybe, as with tools like mobX, you want to have functions be invoked only when the variables they reference change. These could radically simplify the amount of “communication” code that you need to write, and more can concentrate the responses to such changes in a consistent manner rather than force piecemeal edits. This is the role of decorators, perhaps one of the most important capabilities to emerge from the ES2017 upgrades. This post will give a quick primer on ES2017 Decorators.

Decorators

Decorators are familiar to people who work with Babel, but these (and the associated code constructs that these enable, such as those used by Mobx or similar libraries) have yet to make their way into broad implementation natively in most browser engines. As such, you will need to use Babel as a preprocessor for any of the following (or use the ES2015 implementation, discussed below).

Functions are objects. This single fact opens up an entire world in which functions can be “decorated” in various ways in order to expose certain functionality. A decorator, in this context, is a function that wraps around another function in order to provide information to some other process. Decorators differ from ordinary functions in that they do not ordinarily change the result of the function, but rather invoke some additional action when the functon is called, such as adding an entry in a log or indicating that a given parametric class property is observable or not.

The use of such decorators has been around for awhile, and collectively is known as aspect-programming (or, sometimes, metaprogramming). They are, however increasingly showing up in Javascript typically at the point where classes and associated methods are defined. Starting with ES2016, transpilers such as Babel used the @ symbol to indicate such a decorator.

A (relatively) simple example of a decorator might be something like a @log decorator, which is used to identify when a given method is called in a class, along with the arguments applied to that method.

class Mat {
 @log
 add(a, b) {
  return a + b;
 }
 @log
 subtract(a,b){
  return a - b;
 } 
}
var m = new Mat();
m.add(2,3)
m.subtract(2,3)

The two functions add and subtract do exactly what you would expect them to do. However, in both cases these methods have the @log decorator placed on it, which serve to add a log event every time each of these methods is invoked:

Calling "add" at Thu Dec 22 2016 19:02:16 GMT-0800 (Pacific Standard Time) with [2, 3]
Result = 5
Calling "subtract" at Thu Dec 22 2016 19:02:16 GMT-0800 (Pacific Standard Time) with [2, 3]
Result = -1

The log file gives the name of the method and the parameters being passed, along with the time stamp for when the method was called.

In order to create this particular bit of magic, it’s necessary to define the log decorator previously. This would likely be loaded in via an import of some sort from an established library module.The @log decorator itself is defined as follows:

function log(target, name, descriptor) {
 var oldValue = descriptor.value;

 descriptor.value = function() {
  console.log(`Calling "${name}" at ${new Date()} with arguments `,arguments);
  var output = oldValue.apply(null, arguments);
  console.log(`Result = `,output);
  return output;
 };

 return descriptor;
}

Here, the log function is passed a target (the specific function object, the name of that function, and a descriptor that provides relevant information about the function, such as its passed parameters). The old value of the descriptor (which is a function) is temporarily cached in a variable, a log description is sent to the console, and the function is then invoked with the arguments metavariable passed in through the context of the original function (arguments is an array-like object that holds the arguments of the initial calling function).

Given that you have the function and its associated arguments (and with some work the binding class or prototype) this can not only get information but can also be used to populate other control structures. As an example, certain libraries such as Mobx make use of decorators to designate @observable variables. When the value of these change, notifications can be passed back to a reference broker object which will then update items that subscribe to that observable “variable”, without having to write code into the setter/getter directly.

This has incredible utility for React and similar libraries, as these will change UI only when observed variables change. Indeed, this is where the true power of decorators come in: the act of invoking methods that can be passed on to specialized objects without the original author of those methods needing to know the internal mechanisms involved.

About the Author:

A Simple Primer in JavaScript Recursion

December 17th, 2016

Recursion is a concept that is not unique to JavaScript. It is used in all programming languages. Though it is an important part of Javascript that sometimes gets muddled or overtly complex. Recursion is simply when a function calls itself.

A function that calls itself is comparable to a loop. Both of these methods are executing their code multiple times. They also both require a condition to stop an infinite loop or infinite recursion. A simple example of recursion is seen through factoring.

Factorial Recursion

The mathematical concept of a factorial is a perfect case to use recursion. A factorial is represented by (n!). For example, n! = 1×2×3×4×..×n is the main formula. The following examples show the start of a factorial table.

1! = 1
2! = 1×2 = 2
3! = 1×2×3 = 6
4! = 1×2×3×4 = 24
5! = 1×2×3×4×5 = 120
6! = 1×2×3×4×5×6 = 720

The underlying concept of recursion is doing the same thing over and over again. Factorials demonstrate this and can be programmed into a recursive function. The following code is an example of this.

function factorial( n ) {
if ( n === 1 ) {
return 1;
}
return n * factorial( n - 1 );
}

This code fits the correct parameters for recursion. The function is calling upon itself and it has a condition — return, to stop itself from entering into an infinite recursion. This is the simplest demonstration of the concept.

Loop to Recursion

Another great example of recursion can be seen from converting a loop. Take, for example, this simple countdown while loop.

var countdown = 5;
while(countdown > 0) {
console.log(countdown--);
}

When this loop executes, countdown’s value changes with each print out of the subsequent number. This same while loop can be written using a recursive function.

var counter = function(amount) {
if (amount > 0) {
console.log(amount);
return counter(amount - 1);
} else {
return amount;
}
};
counter(5);

The counter is called upon inside the definition of counter function. Each time counter is executed the engine tracks where it’s being called from. The major difference is that this function hasn’t modified the state of the internal variables inside the function. It executes them one after the other. It doesn’t store them and let them stack up on one another.

Tail Call Optimisation

When a function calls itself recursively in Javascript it creates a new stack. A stack is a block of memory that keeps track of the function’s information. Creating a stack causes the JavaScript engine to work much harder and drain memory. This can cause an error if not coded correctly. Herein lies the next example.

function factorial(n, register) {
if (n === 1) {
return register
}
return factorial(n — 1, n * register)
}
factorial(6, 1) // == 720

A tail call function returns the value from the original return value. The last return factorial(n — 1, n * register) line is the tail call. This is a standard way to prevent a recursion from stacking onto themselves repeatedly and draining away all the memory. Recursive functions in JavaScript need to track where they’ve been called every time.

Tail call optimization has become standard in ES6 and they makes sure that each recursion cycle is called one after the other. This avoids stacked up memory. Tail call optimization is considered one of the more difficult methods to learn about. But it is an essential tool in creating or deconstructing a recursion function.

Overall, all of these examples can help guide a developer’s understanding of recursion functions. They are helpful for factoring, looping more efficiently and executing anything repetitive that calls upon itself.

About the Author:

Using JavaScript ASync Functions

December 3rd, 2016

Async stands for asynchronous and it is (aptly) the opposite of synchronous programming. To get a better grasp on Async functions, you need to first fully understand synchronous code. Simply put, synchronous code means “many statements in a sequence”. Each statement is executed one after the other. This also means that a statement has to wait before the other one is finished.

console.log(‘1st’);
console.log(‘2nd’);
console.log(‘3rd’);

The previous code above will execute and output the “1st”, “2nd”, “3rd” strings in a row to the console. Simple. It is written synchronously.

Asynchronous code will execute statements outside of the main flow. This allows for async functions to be executed right away without having to wait. Developers see both states of code. An example of Async programming is shown with a simple jQuery function:

console.log('1st');
jQuery.get('page.html', function (data) {
    console.log("2nd");
});
console.log('3rd');

The output from the example above will be different. “1st”,”3rd”, “2nd”. This is due to the function passing through jQuery.get and not being immediately called. Instead the function has to wait for jQuery to fetch the page before executing.

Async Code: Benefits & Uses

Once the code had run, there is a chance that synchronous code can block future executions. This happens because it is waiting for prior statements to finish. Basically, this means that the UI can become unresponsive until a function has finished. This should be avoided at all costs as it can damper the user experience.

A developer named Brian Terlson, is working on implementing native Async functions into ECMAScript. Currently, it’s in proposal mode and in step three(candidate) of being implemented part of ES7.

Variants of async functions currently exist. The unique keyword is async before every declaration. Here is the following syntax:

  • Async function declarations: async function foo() {}
  • Async function expressions: const foo = async function () {};
  • Async method definitions: let obj = { async foo() {} }
  • Async arrow functions: const foo = async () => {};

Generally, you’ll want to use asynchronous code to perform expensive, time consuming operations. It wouldn’t be used for something simple like changing the CSS class of an element. Here is an example of another async function, but this time with the keyword async in front of it.

 
async function asyncFunc() {
    return xyz;
}

asyncFunc()
.then(x => console.log(x));
    // xyz

Notice the “.then” operator. An async function is passed through the argument by something called a Promise implementation. According to its definition, a promise represents “a value which may be available now, or in the future, or never.”

A promise is in three different states:

  • pending: starting state, not yet fulfilled or rejected.
  • fulfilled: the operation has finished successfully.
  • rejected: the operation has failed.

So to recap, asynchronous code should be used for when synchronous code won’t cut it. It adds a new degree of complexity that will keep your user experience smooth and flowing. Your application or website stays responsive, and reduces idle time for the end user. Native implementation of Async functions will make this a ubiquitous way to execute aysnc functions.

About the Author:

Finding the Most Frequent String in a JavaScript Array

October 21st, 2016

In the following tutorial, I’ll show you how to write a function that takes an array of strings and returns the most frequent string(s) in that array. First I’ll go through the basic concepts and setup, we’ll test it to make sure it works, then I’ll explore a few ways in which you can handle bad data and errors. We’ll also consider some ways to make the outputted data more user friendly. Let’s get started!

We’ll start with a pure function, one that takes an array of strings as input and returns another array as output (the outputted array will ultimately contain the string(s) that occur most frequently in the input). The setup looks like this:

   function mostFreqStr (str) {
      var which = [];
      return which;
    }

Next we’ll define an object that we’ll fill with data, using the strings in the array as keys and the number of times those strings occur as values. We’ll also add in a mostFreq variable that will be used to keep track of how many times the most frequent string(s) occur(s). The code now looks like this:

   function (arr) {
      var obj = {}, mostFreq = 0, which = [];
      return which;
    }

Now we’ll get in to the meat of the function, the processing logic. I’ve chosen to use JavaScript’s native forEach method that is an inherent to all arrays. If for some reason you wanted to use a for or while loop, you could do that as well. Here’s what the forEach approach looks like using ECMAScript 6 syntax (don’t worry, we’ll discuss the logic involved right after looking at the code):

    arr.forEach(ea => {
      if (!obj[ea]) {
        obj[ea] = 1;
      } else {
        obj[ea]++;
      }

      if (obj[ea] > mostFreq) {
        mostFreq = obj[ea];
        which = [ea];
      } else if (obj[ea] === mostFreq) {
        which.push(ea);
      }
    });

The logic is this: the ea variable represents the current array element on each iteration of forEach. The first if statement asks Does the string represented by ea exist as a key in obj? If the string is not the name of a key in obj (i.e., if obj[ea] === undefined evaluates to true), then we declare and initialize in obj the string represented by ea. We initialize it to a value of 1. The value 1 here represents the number of times we’ve encountered the string in arr. On the other hand, If the string is already the name of a key in obj, then we increment that key’s value by 1 (i.e., we add one more to the count of how many times we’ve seen the string in question in arr).

The second if block there is used to compare values of the keys in obj (i.e., the strings in arr) to the current most frequent count (i.e., the value of mostFreq). mostFreq was initialized equal to 0, so if the value of ea in obj is greater than 0 (as it will be as for any string encountered in arr), then mostFreq is updated to the value of obj[ea]. Additionally, the which array gets added to it the current value of ea (i.e., the current string in our iteration through arr). The else if portion of the second if block accounts for the condition where two or more strings in arr share the current value of mostFreq. If two or more strings in arr share the condition of being most frequent in arr, then the latter string(s) encountered is/are pushed to the which array so that they can equitably share the title.

The final step in our function is to return the newly populated which array. The entirety of the code looks like this:

    function mostFreqStr (arr) {
      var obj = {}, mostFreq = 0, which = [];

      arr.forEach(ea => {
        if (!obj[ea]) {
          obj[ea] = 1;
        } else {
          obj[ea]++;
        }

        if (obj[ea] > mostFreq) {
          mostFreq = obj[ea];
          which = [ea];
        } else if (obj[ea] === mostFreq) {
          which.push(ea);
        }
      });

      return which;
    }

Here it is live with a few tests so that we know it’s working:

See the Pen NRLWdz by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

But let’s say we want to make it a little more user friendly with respect to the output. We can convert the which array to a string by using Array’s toString method. We can then append a sentence (using ES6 template literals) in order to clarify the output. Like this:

    which = `"${which.toString()}" is the most frequent string in the array.`

Examples of input and output:

    console.log(mostFreqStr(["x", "x", "y", "y", "y", "z"]));
    //"y" is the most frequent string in the array.
    
    console.log(mostFreqStr(["x", "x", "x", "y", "y", "y", "z"]));
    //"x,y" is the most frequent string in the array.

Hmm… that second one doesn’t look quite right. We can write in some logic to handle our output sentence’s grammar when there’s more than one most frequent string. I’m going to use Array’s join method in order to help us out here. Here’s the live version:

See the Pen kkRaBd by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

There we go!

Now… for one final consideration… error handling. What if someone passes in some bad data? Or let’s say someone tries to pass in two arrays instead of just one; or perhaps an array that contains an element that isn’t a string. What someone tries to pass in data that isn’t an array at all? Let’s write some logic to handle these erroneous conditions. Live example:

See the Pen YGOzRA by Chase Allen (@ccallen001) on CodePen.

And there we have it! A function that takes an array of strings as input, checks for and handles potential errors, and ultimately returns a user friendly response indicating the most common string(s) in the array. Please feel free to comment and share. Thank you for reading!

About the Author:

How to Make Circular/Curved Text with JavaScript

September 28th, 2016

Creating circular text, or text on an curved path, in webpages may seem like somewhat of a intimidating task. There isn’t really a straightforward way to achieve it with standard HTML and CSS. There is a JavaScript plugin or two out there with some pretty decent results, but using plugins means extra dependency and load time associated tacked on to your project. So… what can you do? With a little bit of plain old vanilla JavaScript and standard CSS, it’s actually not that difficult to create curved text of your own! In this article, I’ll show you how to create circular/curved text that relies on as little as 15 lines of JavaScript. The result is functional and reusable so that you can apply as much circular text to your projects as you would like! You won’t need any special libraries or plugins of any sort; just good old fashioned HTML, CSS, and JavaScript. I’ll provide examples as we go, and I’ll provide items for consideration along the way. Circle the wagons; let’s get started!


Circular Text: The HTML

We’ll start by setting up the HTML, which is pretty much as simple as it gets. You’ll want a container for the circular text (although not 100% necessary) as well as a target element in which you’ll insert your circular text. Here’s how I’ve got it set up:

See the Pen ALoKJJ by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Circular Text: The CSS

Next we’ll add a some CSS to get things set up. None of the following CSS is actually necessary, and it can be adjusted as needed. For the purposes of this tutorial, I chose a purely arbitrary blackish background with whitish text; I also chose to center the target element (the div with class=circTxt), but you can choose to position the containers and target elements however you please! Here’s how I have the CSS:

See the Pen NRvNEv by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Circular Text: The JavaScript

Next comes the magic, the JavaScript. Things get a bit more complex here, but the overall logic isn’t really all that difficult. To give a broad overview before actually looking at the code, here’s what we’ll want to accomplish:

  1. Create a reusable function named circularText that takes 3 arguments: 1) the text to be written in circular fashion, 2) the radius of the circle on which the text will lie, and 3) the DOM index of the target class=circTxt element
  2. Split the text in to an array and get it’s length (i.e., the number of characters it contains)
  3. Divide the total degrees in a circle (i.e., 360 deg) by the length/number of characters in the text to determine spacing
  4. Specify the origin, or starting point, for the circular text (for simplicity’s sake, I’m going to hardcode 0 degrees)
  5. Create a loop (here using Array’s forEach method) that inserts the text around the perimeter of a circle using the defined radius and updating the origin/start value as it goes
  6. Call the function to create the circular/arced text!

Got all that? Believe me, it’s really not that complicated; less than 15 lines if you please. Here’s what the code looks like:

See the Pen rrzZoK by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

NOTE: I am do use ES6 syntax there (the arrow function and the template literal), but the code can easily be refactored to comply with more traditional syntax.


Well… there you have it… circular text with plain old HTML, CSS, and JavaScript!

Some things to consider are the need for adjusting the passed radius value based on how many characters are in your text. Generally speaking, the more characters you have in your text, the larger the radius you’ll need to use (however, you can create some neat effects by using a radius that might initially appear to be too small). Also note that you can created arced or curved text without going around a full circle by being purposeful about using spaces in your text.

See the Pen kkobjp by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

The arc effect can also be achieved by modifying the origin value used in the code (i,e., starting somewhere other than at the top of the circle). Regarding modifications to the CSS, the code could be changed to target elements with specified ids or tag names; you could use the document object’s querySelector method to achieve precision targeting as well. Additionally, you can modify both the circTxt containers (positioning them wherever you like on the page, giving them height and width, etc.) and the circular text within.

See the Pen Circular Text Generator by Chase Allen (@ccallen001) on CodePen.

I encourage you to go wild, get creative with it, circle back and have some fun! :)