How To Update Aurelia Javascript Framework

If you are currently working with the Aurelia Javascript framework, then you would know that every so often given the not-so-beta nature of the framework, a new update comes out for one or more of the framework components.

If you’re not staying up-to-date for each update, it is possible to fall behind. While you might assume that jspm update would work. Sometimes if you’re updating an older code-base, the newer code can and possibly will break your application using update.

The best possible solution (as documented by Rob Eisenberg himself in a couple of blog posts) is to to install each top level dependency using jspm install "dependency name" — because it can be a pain in the behind typing out all of those dependencies, here is a shortcut. I am posting this for my own reference, but to also help anyone else as well.

I will do my best to keep this post up-to-date, but as always, check your package.json file and ensure all of your top-level dependencies are listed here as it is possible things are being added, deprecated and removed with each release of the framework.

jspm install aurelia-binding aurelia-bootstrapper aurelia-dependency-injection aurelia-event-aggregator aurelia-framework aurelia-history aurelia-history-browser aurelia-loader aurelia-loader-default aurelia-logging aurelia-metadata aurelia-path aurelia-route-recognizer aurelia-router aurelia-task-queue aurelia-templating aurelia-templating-binding aurelia-templating-resources aurelia-templating-router

Simply paste this into your command line window in your application directory and watch the magic happen. Don’t forget to add in any additional dependencies you might want to update that are not listed above.

Notes:
There might be some dependencies you are using (especially if you’re building off the Skeleton application) that are not included in the above shortcut line. These are:

  • aurelia-animation-css
  • aurelia-fetch-client
  • aurelia-http-client (if you’re still using this instead of Fetch)
 

Reversing A String In Javascript 3 Different Ways

Leading off from my previous post about swapping variable values, I thought I would write a follow-up post on how to reverse a string in Javascript. Surprisingly in Javascript there is no native means of reversing a string (I guess there are very few situations where you would need to do that).

This is not going to be an exercise in code golfing. In-fact, I am only going to show you 3 different ways to reverse a string (although there are potentially tens of different ways to do it). My preference is the first solution using Array.reverse, but pick whatever suits your needs.

This is not going to be about performance or doing the most terse code, this is just a fun little experiment where you might learn a new trick to add to your Javascript toolbox.

Array.reverse:
You’re probably thinking, wait I thought we were reversing a string, why are you using the Array.reverse method. Using the String.split method we are converting our string into an Array of characters. Then we are reversing the order of each value in the array and then finally we convert the Array back to a String using the Array.join method.

function reverseString(str) {
    return str.split('').reverse().join('');
}
reverseString('dwayne');

Decrementing while-loop:
Although pretty verbose, this solution does have its advantages over solution one. You’re not creating an array and you’re just concatenating a string based on characters from the source string.

From a performance perspective, this one would probably yield the best results (although untested). For extremely long strings, the performance gains might drop out the window though.

function reverseString(str) {
    var temp = '';
    var i = str.length;

    while (i > 0) {
        temp += str.substring(i - 1, i);
        i--;
    }


    return temp;
}
reverseString('dwayne');

Recursion
I love how simple and clear this solution is. You can clearly see that the String.charAt and String.substr methods are being used to pass through a different value by calling itself each time until the string is empty of which the ternary would just return an empty string instead of using recursion to call itself. This would probably yield the second best performance after the second solution.

function reverseString(str) {
    return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
reverseString('dwayne');

Got your own solution? Share it below in the comments

 

Swapping Javascript Variables Without A Third Variable

While most developers will probably never encounter a situation where they’ll need to swap two integer values without a third variable unless you’re heavily into code golf.

While novel and impractical for most purposes, it can be nice to improve your problem solving skills and learn new things by solving problems without choosing the most obvious solution.

A little bit of trivia: I was actually asked to swap two integer values in a technical interview once-upon-a-time. So you never know if you find yourself going for a front-end development position and you’re asked during the coding test to swap two integer values without a third variable.

Using an array:

var a = 1;
var b = 2;
a = [b, b = a][0];

Simple math:

var a = 1;
var b = 2;
a = a + b; // a = 3 (1 + 2)
b = a - b; // b = 1 (3 - 2)
a = a - b; // a = 2 (3 - 1)

Simple math condensed:

var a = 1; 
var b = 2;
b = (a += b -= a) - b;

Bitwise XOR Swap:

var a = 1;
var b = 2;
a ^= b;
b ^= a;
a ^= b;

ECMAScript 2015 (formerly ES6) Destructuring:
This is my favourite solution of them all. It feels the cleanest, the intent is clearer and it doesn’t rely on any hard to follow math or operators to swap values.

var a = 1;
var b = 2;
[a, b] = [b, a];
 

JSPM vs Webpack

Life on the front-end side of the development tracks can be an exercise in patience and learning endurance. When it comes to front-end package managers, there is definitely no lack of choices.

In this article I will be focusing on two of the hottest front-end tools: JSPM and Webpack. I have decided to leave Browserify out of this as I believe it has been covered enough and sadly in my opinion, the future currently doesn’t have a place in its heart for Browserify.

What is JSPM?

To quote the JSPM site itself, JSPM is “Frictionless browser package management” – basically it allows us to manage our front-end dependencies. While on the surface this might not seem that impressive, hey we already have Bower and NPM for that, the approach JSPM takes is quite clever in that it compliments sources like NPM and Github, rather than providing its own hosted packages platform. It isn’t just another package manager, it aims to be THE package manager of the front-end.

It is built on-top of SystemJS (which was created by the same developer) which in itself is based on the es6-module loader. This allows us to load modules/files using a plethora of different syntaxes to accommodate to all preferences; CommonJS (like Node.js modules), AMD (RequireJS specification) and ECMAScript 2015 modules (aka ES6).

You’re probably thinking, but don’t we already have package management in the form of; Bower, NPM and various other managers? Yes, we do. But very few can allow you to install packages from Github and NPM, then bundling them all without having to install any other tools or configure anything.

While the package management and SystemJS functionality is great, JSPM also offers bundling as well. So not only can we manage all of our front-end dependencies using JSPM regardless of source, we can also bundling them all up a variety of different ways; self executing bundles, single bundles and multiple bundles all management by a mapped tree in the config.js allowing for intelligent code splitting and loading in our applications.

What is Webpack?

Webpack is a module loader and bundler akin to Browserify. It actually offers almost everything that JSPM does except it seems to suffer from a lack of focus on ECMAScript 2015/2016 specification support out-of-the-box (although there are plugins for it) and lack of package management (similar to Browserify). So while there is overlap between Webpack and JSPM, there are fundamentally large differences between the two.

There are numerous plugins out there for Webpack that take it from being just a code bundler to something more. The ability to parse CoffeeScript, parse and base64 encode images, include static assets like CSS and use Node modules on the client side is pretty awesome. It is a highly configurable code bundler that can handle pretty much sort of front-end code and asset there is.

Why JSPM?

At its core JSPM is nothing more than a polyfill for the proposed ECMAScript 2015 module loader specification which is actually thanks to the SystemJS loader integration. What this means is that we can write the code of tomorrow today.

Instead of relying on a third party application, we can write ECMAScript compatible code and import it where needed knowing that when the module loader API is more widely supported the SystemJS dependency can be removed entirely.

The power of JSPM actually lies in its ability to manage dependencies from multiple sources and bundle them. Another major benefit being you don’t need any form of build tool or task running to compile your code (at least during development).

You also don’t really need to touch any of the configuration either and it works out of the box with both BabelJS and Traceur for transpiling. The lack of build step during development means you don’t need any watchers or anything running to see your code working.

Want to install a dependency using Github as a source and then map it to the namespace “mypackage” type jspm install mypackage=github:owner/reponame and you can now import code using ES 2015 syntax import {SomeClass} from 'mypackage'; and thanks to the automatically generated dependency tree in config.js JSPM knows about your package and where to load it from.

If you prefer the approach of using polyfills opposed to workarounds and non-specification compliant hacks, then JSPM is the bridge between the now and the future of the client-side web.

Why Webpack?

If out-of-the-box support for ES6 modules does not phase you and you are happy to manage your dependencies yourself, then Webpack is still a decent option that a lot of people opt to use. It still requires a little configuration to work with ECMAScript 2015 code, but it isn’t by any means a deal breaker. This seems to ring true for Webpack as a whole, it requires a bit of configuration to tell it what you want to do and assumes less of your workflow.

Really when you look at it, Webpack is JSPM without its SystemJS loader and package management features. So if you’re not even writing ES 2015/2016 Javascript or managing a lot of third-party dependencies, you probably won’t see the value with JSPM as much as you would using something like Webpack.

Conclusion

Solutions like Browserify and Webpack are in my opinion hacks because they highlight the shortcomings of HTTP/1. If you’re after something that can handle your dependencies and allow you to write specifications compliant future Javascript for the client-side, I would choose JSPM. It offers so much more, requires far less configuration than Webpack and thanks to the SystemJS integration, allows us to write the Javascript of tomorrow today.

While JSPM might not be seen as important now in the face of existing tools, when HTTP/2 and its handy multiplexing is more widely supported, tools like JSPM are going to be at the forefront of package and dependency management in the long run as hacks like minification and bundling soon become unnecessary in an attempt to make our web applications faster.

 

Increase Galaxy S6 Performance: Disable DVFS

As much as I love my new Samsung Galaxy S6 Edge, it does suffer from some bad performance issues at times. Even playing non graphically intensive games or applications can produce noticeable lag.

While the hardware in the phone is definitely not sub-par, a certain feature on Samsung phones since Jellybean called Dynamic Voltage and Frequency Scaling (DVFS) can have an effect on the phones performance.

Without going into too greater detail, DVFS causes the phone to scale down CPU performance to prevent the phone from getting too hot. The more power being consumed, the more heat generated. As a result, the phone will encounter lag when playing a 3D intensive game or CPU intensive application.

How to disable DVFS

First and foremost, you need to have a rooted Samsung Galaxy S6. If your S6 is not rooted, then I do not think there is a way to disable DVFS reliably without a rooted device.

  • Step 1: Download ES File Explorer from the Google Play store. It is a free download.
  • Step 2: Slide out the left drawer, under tools turn on Root Explorer.
  • Step 3: Now head on to the System partition, then the sys folder. The exact location you want to end up in: sys > devices > 14ac0000.mali
  • Step 4: Find the file dvfs and then long press it. You want to now open up the permissions dialog by going to: More > Properties > Permissions
  • Step 5: Now uncheck all of the permissions on the permissions dialog so no box is ticked.
  • Step 6: Now do the same for two other files in the same folder dvfs_min_lock and dvfs_max_lock. Unchecking all of the permission boxes.

That is it. Your S6 will now be more noticeably faster and snappier when navigating between applications, playing games or doing anything that might make the DVFS trigger and slow the phone down.

 

TypeScript vs ECMAScript 2015/2016

As Javascript slowly becomes a less salty language thanks in part to ECMAScript 2015 (formerly ES6) amd ECMAScript 2016 (formerly ES7), the question of whether to choose a superset of the Javascript language or write POJ (Plain Old Javascript) is a question we need to ask ourselves.

My experience with TypeScript is rather minimal, whilst investigating Javascript frameworks a few months ago I used TypeScript for a little while to get a feel for it and see what it would offer me in terms of workflow and efficiency. The fact the project would be built in .NET which means using Visual Studio 2013 was also a point towards TypeScript (of which Visual Studio fully supports).

What does TypeScript offer us?

For a long time Javascript has suffered from some pretty serious flaws, which supersets and compile-to-Javascript languages like CoffeeScript have tried to solve. TypeScript takes the concept a step further and gives us strong typing and static compilation. It allows us to discover flaws in our code before they’re pushed into production, if your code isn’t valid, it won’t compile.

Whilst we can achieve the same thing in conventional Javascript, it usually requires the use of one or more front-end CLI tools that check our types, ensure our code adheres to the styleguide, handles minification and ensures that everything will work in non-spec compliant browsers.

A handy feature of TypeScript courtesy of its strict types is that it addresses issues with the loose equality operator ==. In conventional Javascript doing so would coerce the types, converting them before they are compared. In TypeScript however because you defined the types being compared beforehand, TypeScript knows when you’re trying to compare using == two values with non-matching types like Number and String and produce an error.

It also addresses a few other quirks in Javascript that I won’t go into. It is worth pointing out that TypeScript obviously doesn’t fix Javascript, but because it compiles to Javascript, it prevents us from making basic and sometimes hard to see errors in our code before we even get to run it. Your TypeScript code is compiled to resemble the good parts of Javascript. You get classes, modules and all of the other nice features that we’ve grown to love in ES2015 and future specifications.

You also have to factor in to the equation that TypeScript made its debut in 2012, before we had the great choice of front-end tooling and support we do today thanks to the concentrated efforts of the TC39 committee.

If you’re working in a large codebase (the purpose of which TypeScript was originally designed for), then there is a benefit to TypeScript how it strictly enforces types. It is more verbose and designed to catch errors earlier before they’re introduced into a codebase.

If you’re already working with a language such as Java or C#, then you will probably hate Javascript itself and prefer to use TypeScript instead which will feel right at home. Using TypeScript within a C# heavy project makes a lot of sense and helps reduce the context switching efficiency drop you traditionally run into when switching from front to back-end (or vice-versa).

While TypeScript offers many other features, the strong typing is definitely the biggest and unique aspect of TypeScript that sells it. As witnessed in TypeScript 1.5, a lot of ECMAScript 2015 features were rolled into it and presumably TypeScript 1.6 will roll in more features from the current and future specification.

What does conventional Javascript offer us?

Before transpilers like Babel hit the scene, we had Google Traceur and while it allowed us to write future Javascript, we didn’t have support for at the time only early draft concepts of what ES2015 would look like. In 2012 we didn’t have much, in 2015 we have a lot of choice.

In the latest spec we get; classes, arrow functions, modules, let and const, for..of iterator, enhanced object literals, generators, weakmaps, proxies, symbols, promises, tail calls, reflect api, module loaders and plenty more. It turns out your regular run-of-the-mill Javascript has grown up, it offers the kind of things we could only dream about 5 years ago.

However, conventional Javascript still lacks static types. But is being able to verbosely define your types that big of a deal in Javascript? The benefit of types (besides preventing errors) is they make it easier for other developers to understand your code.

However, given that ES2015 finally brings order to the court of Javascript, IDE’s like Webstorm are now able to appropriately check your code (especially now we are not all using different implementations of prototypal inheritance).

Conclusion

As much as I think TypeScript is great, I believe using it is a niche preference that boils down to; if you’re comfortable with C# or Java, you use Visual Studio as your IDE of choice, you have a lot of type guards in your code (instanceof checks), you are working on a massive codebase and finally: you work on a large team and you want to avoid styleguide clashes, ensure that all developers are writing the same code, the same way.

TypeScript is a great way to ensure that code is consistently written and appropriately checked before being compiled to Javascript and pushed into production.

If you don’t fall into the above categories, then standard Javascript is also fine. Honestly, at the end of the day, TypeScript and Javascript are the same thing, they’re both Javascript, one is just more stricter and C#/Java like than the other.

At face value, the only difference between TypeScript and Javascript is the static types and honestly, if you can live without needing to declare your types and you’re using other tools that catch your coding errors (or a great IDE), then TypeScript looks the same as modern Javascript. If you need type checking, you can always just use instanceof and typeof to check types before using/mutating them.

 

Recreating Facebook’s Celebrate Pride Rainbow Overlay 3 Different Ways Using CSS

You’re probably aware of Facebook’s pride image overlay effect which allows you to add a gay pride flag overlay on your Facebook profile image. Today we are going to be recreating this incredibly simple effect, three different ways. First we will do it the Facebook way, followed by a couple of other approaches.

To demonstrate the effect I have created three Codepen’s so you can see the effect in action and fittingly used a picture of Donald Trump and his son to demonstrate the pride effect.

1. The Facebook way using CSS filters and opacity

The way Facebook approaches the effect (during the creation process) is through the clever use of opacity and if you’re using a supported browser, CSS filter effects. As you would expect, each bar is merely a DIV with a height of 100% divided by the total number of bars (in this case it is six). The live preview you are seeing is not necessarily what the final effect will look like because CSS is being used to give you an instant preview, the final effect looks much nicer as it is done server-side via an image processing library.

In unsupported browsers, Facebook simply just don’t use any CSS filter effect, relying on the opacity on the image container to dull it down enough so the rainbow bars shine through. This means anyone using an unsupported browser will not see the true effect (at least not during the creation process) until the final version is saved and the processed image is returned.

See the Pen mJXjGV by Dwayne Charrington (@DigitalSea) on CodePen.

2. CSS blend modes

Unknown to some, the CSS specification has support for blend modes like; multiply, hard-light, soft-light and so on. The kind of effects you are probably aware of in Photoshop and perhaps the kind of effects your overzealous designers have asked you to painstakingly implement at some point or another.

Because the blend modes require a background image at present, we will be using an image that Wikipedia has of the gay pride flag which we will overlay on-top of our image and use the blend effect. We will be using multiple background images to achieve our effect without multiple elements.

The end result here isn’t as nice as the other two options, I will admit I didn’t spend a lot of time playing around with different effect combinations. You can experiment around with the different blending modes to achieve different effects by reading up on background blend modes here.

See the Pen xGYJMN by Dwayne Charrington (@DigitalSea) on CodePen.

3. Vertical stacked CSS rainbow gradient

Now lets recreate the effect using CSS linear gradients. Through some trickery, we can actually have harsh colour stops for each coloured bar. It takes a little extra messing around (as you can see looking at the CSS) but the effect looks pretty damn good and is the most cross-browser friendly compared to the other two.

In the below Codepen example we have the gradient example, and also different combinations using opacity, background blend modes and CSS filters to show how different effects can be used together.

See the Pen LVQJYE by Dwayne Charrington (@DigitalSea) on CodePen.

Conclusion

CSS is awesome and the gay pride image overlay is a simple and nice gesture towards the community. Hopefully you’ve learned something or perhaps have some ideas on how you can apply the above effects to other aspects of your designs and websites.

 

Abstract Classes In Javascript

Modern Javascript is a lot different to Javascript of 2010. We have considerably more methods and means of doing things that we did not have previously. Some of those include classes, generators, arrow functions and a few other high-profile additions.

One aspect of Javascript that not even ES2015 nor ES2016 covers is the concept of abstract classes. The ability to specify a class that defines how child classes should look, more specifically ensuring they specify certain methods.

Recently whilst working on an Aurelia project, I was building a widget based system where a base widget class defines a few core values and methods, then the child class which is a certain type of widget extends and defines the contents of the widget.

One such requirement was the base widget class cannot be instantiated. Another requirement is all child widgets must implement a schema method which returns the schema for a particular widget.

Preventing base class from being instantiated

Due to how classes are implemented in ES6, we can check the constructor knowing that any class that extends the Widget class is going to have a different constructor because it’s a new class and therefore a new instance. We just check in the base widget class if the constructor is “Widget” or not. If it is, we can assume someone is trying to instantiate the widget class directly via: let myInstance = new Widget() which our code will stop.

class Widget {
    constructor() {
        if (this.constructor === Widget) {
            throw new TypeError('Abstract class "Widget" cannot be instantiated directly.'); 
        }
    }
}

Enforcing implented methods

To require an inherited child class implements our required method, we can check for its existence via this which allows us to see if the required method has been defined. We will take the above example and add in another check for our child class method.

class Widget {
    constructor() {
        if (this.constructor === Widget) {
            throw new TypeError('Abstract class "Widget" cannot be instantiated directly.'); 
        }

        if (this.schema === undefined) {
            throw new TypeError('Classes extending the widget abstract class');
        }
    }
}

class PieChart extends Widget {
    constructor() {
        super();
    }

    get schema() {
        return {
            "name": "PIE_CHART",
            "data": []
        }
    }
}

Conclusion

We might eventually get a native solution, but for the moment we can easily implement our own fake abstract class implementation in Javascript using classes and it will work for most purposes. I haven’t encountered any issues with the above solutions.

 

Developing A Multilingual Website? Develop In A Different Language

This isn’t a tutorial but rather a public service announcement. If you’re building a website that is going to be viewed in multiple languages, then you should be developing the site in a language other than the native language (in most cases English).

It seems like common sense, but you would be surprised how often different languages and responsive development are not considered at the same time.

Whilst working with an American video streaming platform startup last year the audience was going to be English and Spanish speaking countries. Naturally the designers only bothered to design everything in English, so when it came to building the site a lot of issues were encountered thanks to many single English words being two or more different words in Spanish.

Sometimes the issue of a Spanish word or sentence being longer could be solved by making the overall font size smaller. For some aspects however where space is constrained, it got to the point on a couple of occasions where the designers had to redesign parts of the application to account for different languages (buttons and promotional banner images with text mostly).

Even if you don’t offer native language translation on your site, if a user visits your website and is using Chrome, Google will offer to translate the page into the visitors native language (sometimes automatically if the setting is enabled to do so). This means you can no longer assume that the language you build the site in is the language it is being viewed in (even if you don’t offer the option to change). This can negatively impact the layout of your site or application without you even realising.

What actually prompted me to resume writing this post which has been in a draft format since November 2014 was a submission I saw on the Web Development subreddit. A user who viewed the Windows 10 promotional site in both Italian and English noticed a few responsive aspects were inconsistent and broken because the developers obviously only tested English.

I don’t develop multi language websites that often, but based on previous experience I know that assuming the site will look and function the same way for all languages is a recipe for trouble. I found Spanish to be somewhat troubling especially for buttons, so if you offer that language as an option, develop in Spanish first.

 

Green Smoothies

For about six months or so I have been consuming a homemade green smoothie every morning for breakfast. Some people are on the fence about them which is understandable, from the outset they look like cups of fruit and vegetables.

The reason I decided to start having them was due to the fact I did some contracting for a startup in the US and I ate a lot of bad food. The startup lunch culture is intriguing, nobody brings their own lunch, you all go out and eat out as a team. I am guilty of having Mexican food a few too many times for lunch, not the healthiest option either.

Maybe it is just a coincidence but I have noticed a few things that I would attribute to having a green smoothie everyday. It could just be in my head, I don’t want to go all crazy on you and proclaim that green smoothies are the cure for cancer like some would have you believe.

About 1 month ago, everyone at work had the flu. I literally mean over the course of about two weeks, the flu spread throughout the office. It wasn’t just any flu, it seemingly had enough impact to knock people out for an entire week, the other developer I share a cubicle with was out almost two weeks.

Weirdly enough, I was the only person who didn’t get sick. I felt like perhaps I exhibited a few flu signs (mostly sneezing), but I didn’t miss a day of work and I never felt like I actually got sick at all.

Then my fiance got sick, she had the flu for about a week. Being pregnant, she only occasionally has a green smoothie with me. I didn’t go out of my way to stay away, we still slept together and stayed close: I didn’t get sick. I did wake up with a minor sore throat, but I think that was due to sleeping with my mouth open and the fan on the high setting.

Besides the potential boost to my immune system, I feel like I have more energy and I am definitely more regular thanks to the fibre in the skin of the fruit and other various additions.

Green Smoothie Recipe

If you’re interested, here is what I put into my smoothie. Some people put coconut milk in and other needless things, this is what I put in.

Also keep in mind I only wash the fruit and vegetables, I don’t take the skin off anything.

  • 2 cups of spinach (minimum)
  • A few pieces of kale (it is expensive, so it usually isn’t available and can be optional)
  • 1 carrot
  • 1 banana
  • Half a lemon squeezed (including the seeds)
  • 1 apple (red or green)
  • 1/2 orange (if we have them)
  • 1/2 cup pineapple (if we have it, fresh only)
  • 1/2 cup watermelon (if we have it, include some of the green/white part)
  • 1/2 cucumber (optional, waters it down a little more)
  • 1 teaspoon ginger
  • 1/2 teaspoon turmeric
  • A handful of grapes (if any available)
  • Some ice
  • Half a cup of water (add more of less depending on desired thickness)

Blend it all up and enjoy. Keep in mind the first few days your body will get a shock, so you might experience a few constant trips to the bathroom (not diarhea, but just a few sudden urges like you have had too much coffee).

As always, make informed choices about what you consume. This is my opinion and I only ever have one per day for breakfast, usually with a coffee and a slice of toast with butter and Vegemite.

I’m not a health nut or condone diets like Paleo, but I also acknowledge I don’t consume the recommended amount of fruit and vegetables everyday, the green smoothie helps substitute that.