# Altitude of a Triangle With d3.js

I’m back at college learning the maths that I should have learned a long time ago. I am also trying to kill 2 birds with one stone by using what I’ve learned to help me learn d3.js at the same time. The task I set myself this week was to draw the altitude of a triangle through a point.

In geometry, an altitude of a triangle is a line segment through a vertex (point) and perpendicular (i.e. forming a right angle with) a line containing the base (the opposite side of the triangle). This line containing the opposite side is called the extended base of the altitude.

My first steps are to create a scale that is of much lower resolution than the finely grained pixels and below is the code that creates both the scale and the axis. I blogged about scales in more detail in my last blog post:

I then created 3 arbitrary vertices for my triangle that would fill the x and y axis as much as possible:

My next task was to then try and draw a triangle from these points. Below is what I ended up with before I explain the solution:

After a bit of trial and error by first of all trying to draw lines with the line function, I came across d3’s path function:

This is effectively a DSL or mini-language for drawing shapes.

I’ll add a translation for each line:

• `'M ' + a.x +' '+ a.y +` - This means place a point at the x and y coordinates of the point I previously created with `var a = {x: xScale(1), y: yScale(1)}`. This is analgous to the starting point where you might place your pen.
• `' L' + b.x + ' ' + b.y +` - This means draw a line created from the point created above to the point `b` that was declared like this `b = {x: xScale(6), y: yScale(18)}`. Because we are using scales, we can pick nice friendly points like (6,18) rather than the harshness of pixels.
• `' L' + c.x + ' ' + c.y +` - draw a line to the c point
• the `z` command closes the path.

I really like the path function as it is how a human would draw a triangle with pen and paper and is very easy to grok.

With the easy bit done, I now wanted to draw the altitude through point A that would be perpendicular to line BC.

If I was doing this with pen and paper, I would perform the following steps:

1. I would find the gradient (or slope for those of you from the US) of the line `BC`.
2. I would use this gradient/slope to create the equation of the line in `y = mx + c` format.
3. I would find the perpendicular gradient/slope of `BC`that I can use to create an equation of the line that will go through point `A` and will be perpendicular to point `C` in `y = mx + c` format.
4. I would then solve these simultaneously to find the point of intersection from point `A` to the point on `BC` that was perpendicular to point `A`.

What I quickly found out was that transfering pen to paper calculations to machine instructions or javascript was extremelly difficult and different. Here are the steps I took:

Like in the pen and paper version, I found the grandient of `BC` and created this function:

I then created a function to find the perpendicular gradient using the graident found in point 1:

In order to get both line equations into `y = mx + c`, I needed a function that would take a point and a gradient and give me the `y-intercept` or the point where the line cuts the y-axis:

I could then get the y, mx and c values of `y + mx = c` for both lines so I could solve the equations simultaneously.

I would use the substitution method or the addition method to solve a series of equations with pen in paper but writing it in code was a different matter and matrices seemed like the obvious fit. Please write a comment below if there is a more efficient way. There is cramer’s law which seemed ideal for my needs. I needed to get my vars into the following format:

Below is my altitude function that gets the values into matrices before passing to a function that will use cramer’s law to find the point of intersection.

Below is the function I used to first of all find the determinant of the matrix before applying cramer’s law:

The above returns a point that I can then use to join point `A` to the point of intersection returned from the `solveMatrix` function.

I want to add drag and drop to rotate the triangle so I’ll probably need to put checks in for vertical and horizontal values for x and y but this will do for now.

Below is the end result of my troubles with the altitudes of all three vertices shown.

The hardest part was to solve the simultaneous equations and I belive there is a better and more efficient way that uses vectors to work this out but I have not covered this with my course as yet.

Here is a working jsbin of my efforts.

# Grid Lines and the Equation of a Line With d3.js

I’ve recently gone back to college to do a higher maths class at night and I want to use some of the concepts I am learning in my programming to enforce what I have learned so far. I’ve been meaning to learn d3 for some time so this seems like a perfect opportunity to kill two birds with one stone. I thought I would start with something simple and have a draggble line that shows the equation of a straight line with respect to the two coordinates at the end of each line. The equation of a line may still exist in the memories of your shool days.

Here is a jsbin with the product of my fumblings. You can drag the line by either of the red circles at each end and the calculations will recalculate.

Below is the end result

I will now breakdown the code:

The first code blocks create an x and a y scale that will scale from 0 to 20 units in each axis which is preferable to using the much more granular pixels. These scales are used to create the labels on the x and y axis and also make positioning elements much, much easier.

• Lines 1 to 3 simply define some dimensions for the document and a margin.
• Line 5 - 7 and lines 8 - 11 create an x axis and y axis respectively which will use the available width and height to spread out the 20 units of scale across each axis.

## Scales

The definition of a scale from the d3 wiki is:

Scales are functions that map from an input domain to an output range.

Scales transform a number in a certain interval (called the domain) into a number in another interval called the range. If we look at the code used to create the x axis scale:

The code above returns a converter function and binds it to the variable `xScale`. We will use this function a lot to convert the `x` coordinate of a point from the real pixel value into the `0 - 20` output range scale we have specified. The code specifies that the scale is linear and that it has a minum value of 0 and a maximum value of 20. This is achieved by passing the array `[0, 20]` as an argument to the `domain` function on line 2 of the above. The code on line 2 then specifies the `range` that is used to equally space out the 0 to 20 units. In this example we are using the available width of the svg document.

The exact same logic is used to create a converter function for the y scale but this time, the height of the svg document is used as the `range`.

The next step is to draw the x and y axis complete with graduated labels. The following code creates the x axis:

The x-axis looks like this:

• The call to `d3.svg.axis` on line 1 unsurprisingly returns an instance of the axis object.
• Line 2 makes a call to the scale function and passes in our `xScale` converter reference we created earlier. The labels or ticks as they are known as in d3 speak will be graduated with respect to the `[0, 20]` domain array of min and max values we specified.
• Line 3 positions the axis at the bottom of the document.
• On line 4 the `innerTickSize` function of the axis object is called to create the horizontal lines that are vertically aligned from each label or tick. I struggled with a good way of creating the gridlines for a long time and it turns out you need to pass in a negarive argument like `-height` in line 2 of the above because we want the lines to fill the full document and if we do not pass a negative value then grid lines flow down from the labels and not up. You can see this by adding and removing the line from the jsbin.

The yAxis is created in a similar fashion only the horizontal grid lines are creating by passing in `-width` into `innerTickSize` to create the horizontal lines.

Positioning the line and circles was very easy after I had my grid created and my scales set up. The line is created below:

• Line 6 creates an svg g element or container that can be used to group shapes together.
• Lines 11 to 14 specify the start and end points of the line. What is important about this is that the `xScale` and `yScale` converter functions are used to place the line on the 0..20 scale.

The circle and text label objects that specify the coordinates of the end points follow a similar approach:

What is interesting about the above code is the `data` function call on lines 5 and 16. I liken this to data binding and a circle or text object is created for each element in the `lineData` array on line 1.

What I found confusing about the above code when I first encountered it is that `selectAll` works on elements that you are going to create rather than what you have created. The `enter` function on lines 6 and 17 is used to add the new elements to the document as the data changes.

All that is left is to display the code that handles the drag events:

The above code creates a drag function that I can attach to elements of the document.

I struggled for a while with getting the correct text for labels of the coordinates of the end points of the line and the main header label. The drag event handler on line 3 gets passed a `d` argument which is a d3 behaviour object that has the x and y mouse cooridinates of where the mouse was dragged to. I had to use `xScale.invert` and `yScale.invert` to get the correct scaled cooridinates for the text labels. The invert function returns the inverse mapping of range to domain. The rest of the code just positions the elements to the new mouse positions.

The drag function is then attached to each circle as it is created on the last line of the code below;

# Emberjs - Detail View Without Switching Routes

Rendering long lists of tabular data on the client is something I have spent a lot of time on and this dates back to my backbone days. You need to at the very least employ infinite scrolling which opens up other cans of worms. What if my tabular data has a cell with a link and I click the link and then click the back button. Unless I spend a lot of engineering effort, I will have lost my place in the infinitely scrolled list.

This was a problem I recently faced on the application that I am working on. We have a large table of infinitely scrolled rows of contact data that had links to the detail of each contact on each row. We started off with the links redirecting to a new route that displayed the individual contact’s details. This meant that when you clicked the back button from the detail view, the table would be re-renderd from scratch.

I came up with quite a nice and not so technical solution that avoided many dark hours of development. I came up with the idea of sliding out the view of the contact detail from the same route that contains the table. This means the user never loses their place in the table. Throw in some css3 animations and I am very happy with the solution. Below is an animated gif that shows what I have christened the `x-drawer` component:

Here is a working jsbin which shows the code in action. The `x-drawer` component is a container for other components and is declared in its nested form and any component can be placed inside it:

I actually use the component helper in the production app as I now use the drawer a lot but in the above gist I simply have a property `showDetail` that when set to true will activate the drawer.

The `x-drawer` component is actually very simple and the sliding animation is achieved with css3 animations and specifically css transitons that enables the drawer to slide out slowly rather than just appear. I used a combination of `translateX` and `transform` to slide out the view.

Another requirement that I had thrust apon me was to make sure the drawer was closed if the user clicked anywhere outside of the drawer. Below is the code that creates an overlay on the remaining screen real estate that when clicked sends the action to close the drawer:

This was actually quite a simple solution to a difficult problem. My first thoughts where that I need to work on the performance of rendering the table but with this solution, the table is always present as we don’t have to naviagate away.

# Functional JavaScript in the Browser and Why I Should Care

Why should you care about functional javascript? I’d heard of the merits of functional programming for a while now and up until recently, I thought that the main benefits of functional programming where really only applicable when dealing with highly concurrent programs when functional programming can help guarantee thread safety. Writing side effect free functions that use immutable data structures rules out interaction problems between threads that mutate data. All well and good but why should I care about any of this in the single threaded realm of the browser?

The pendulum between server heavy app and client heavy app. has swung back to the client again for this epoch and single page applications are all the rage. This would have seemed like insanity at the turn of the century but advances in browser technology and a demand for more ambitious applications has led us to the now infamous `SPA`. Our programs live a lot longer in the browser than they used to. Gone are the days when we could rely on a browser refresh to reboot the browser code and rebuild clear all our objects from memory. `reactjs` has come up with a beautfiul top down, one way data push that can simulate this behaviour by abstracting away that gargantuan side effect known as the DOM into a virtual DOM to diff against the previous state. Reactjs has embraced functional programming and so should you.

## Side effects, function Purity and Referential Transparency

Functional programming favours functions that, for a given input, will consistently return the same output. A pure function does not depend on and does not modify the state of variables outside of its scope. When a function performs any other action, apart from calculating its return value, the function is impure. A program or function is said to have side effects if it can produce different outputs given the same input.

A very simple example of a pure function is below:

Referential transparency is the ability to freely replace an expression with its value and not change the behaviour of the program. We can show that the `mult` function is both pure and `referentially transparent` with the code below:

Replacing the call to `mult` with the result does not alter the output of the computation.

Below is an example of a function that relies on a global variable to calculate its output:

We can clearly see that providing the same input each time does not give us the same output each time.

Side effects are functions that rely on the outside OR can be functions that alter the outside world. The ubiquitous `Hello World` program is actually a side effect because it alters the state of the output on the screen. A call to `console.log` is a side effect. All IO is side effect laden, reading a file from a disk is a side effect because it might throw an exception because the network is unavailable. We therefore cannot guarantee the result of calling the function.

Any function that does not return a value will more than likely have side effects because it is probably mutating some external state.

Our programs would not be very practical without side effects and the goal of functional programming is not to eliminate side effects but instead we want to limit them and also more importantly, isolate them. How can we limit side effects in the sea of mutation that is javascript? The first thing we can do is to use immutable data structrues.

## Immutable Data Structures

I think the penny is starting to drop with many in the javascript world about how sensible immutable data structures are. A data structure is immutable if it cannot be changed after it has been created.

In the chaotic realm of the single page application, I find it very reassuring to know that after I have created an object or assigned a value to a variable, it will not be changed by some well meaning code outside of my control. A lot of SPA frameworks use two way data binding to bind objects to DOM elements or other structures. I have also had hellish results with using observation through `Object.observe` or some other mechanism of reacting to state changes, I now consider this to be an anti-pattern.

es6 has introduced the `const` keyword which is analogous to `final` in java, it does not mean that all data structures defined with the `const` keyword are immuable but it does mean they cannot be reassigned once they have been assigned. The code sample below will illustrate this:

If we want full immutability then we can use something like immutable-js or mori. Both libraries provide persistent data structures for your use. The data structures are called persistent because they always presist a previous version of themselves when modified.

Below is an example of `immutable-js` that illustrates this:

You can see from the above that we can check equality by value and not reference on `line4` when comparing `list1` and `list2`.

Also illustrated is how `map2` returns a reference to `map1` on `line 7` because no change was made to the underlying hash and on `line 11`, `map1` remains unchanged and a new version of the data structure is returned after changing or adding a new value to part of the data strurcture. I hope you can see how we could use persistent data structures to trivially hookup undo and redo functionality (more on this later).

## Statelessness

Imperative programming works by changing programming state to produce answers. Conversely, functional programming produces answers through stateless operations.

This brings us back to function purity, our programs are easier to reason about if we can be sure that given the same input, we get the same output. We want to avoid functions that reference member variables or any thing outside of the functions environment wherever possible.

## Back to the Real world

Here are some things to consider everytime you create a function in javascript:

• Are my functions dependant on the context in which they are called, or are they pure and independent?
• Can I write these functions in such a way that I could depend on them always returning the same result for a given input?
• Am I sure that these functions won’t modify anything outside of themselves?
• Pass values as parameters, don’t store state in member variables.

I blogged here here about using a real world example to limit side effects in an emberjs application and here about how you can use persistent data structures in an emberjs application to implement basic undo and redo functionality.

## Higher Order Functions

A higher order function is either:

• A function that takes a function as an argument
• A function that returns a function

I am going to concentrate on the latter and I am going to first of all use partial application.

Wikipedia gives the following definition of partial application:

partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity

If we return to our `mult` function that I showed in the beginning, we can create a new function `double` by using partial application:

On `line 3` of the above, I am using the lesser known property of bind that after the first argument where you can specify a context, every parameter after the first will be prepended to the list of parameters when invoking the bound function.

We could rewrite the `double` to return a function like this:

We now have a `makeMultiplier` that can create many different types of functions based on `mult`.

A more practical use of a higher order function is the `maybe` function below that can take a function and return a null safe version:

Here we create a new null save function that is returned from the `maybe` function. We can now create other functions from this `maybe` function that will handle null values.

### Composability

Another benefit of higher order functions is to take 2 or more functions and combine them into one. Below is an `and` function that will perform a logical and on the output of two functions:

### Further down the rabbit Hole

There are a number libraries that go much further with respect to functional programming:

• omniscientjs
• Built on top of reactjs
• Top down rendering
• Immutable Data
• OM
• Built on top of reactjs
• Written clojurescript
• ClojureScript’s immutable data types
• Purescript
• Type system
• Bindings for reactjs and angular
• Elm
• Compiles to HTML and javascript
• Compiler guarantees no runtime exceptions

# Clojure - Idiomatic Refactor From Recursion

I’ve become addicted to solving programming challenges that you might find at hackerrank or 4clojure. I spend most of my day job in `emberjs` and as much as I find myself agreeing with `reactjs's` take on things, I simply don’t have the energy or the will to learn another javascript framework. I also think it is bad to learn another way to do the same thing in your spare time. You need to push your brain into interesting and new avenues.

I’m using `clojure` to solve these programs and it is quite nice to not have to worry about persisting data or learning the latest du jour framework.

I have found myself using the same pattern over and over again when iterating a sequence that might decrease due to some condition and accumulating a value while doing this. Below was my bog standard way of doing this:

The above code reduces each item in the sequence by the smallest value and then filters out any values that are zero or less (lines 2 and 3). If there are any values left, the function recursively calls itself until the sequence is empty. On each call to the function, the count of remaining elements in the sequence is added to an accumulator argument `acc`.

I have been using this pattern for a while now but it did not seem to me to be idiomatic clojure. I did some research and the refactoring below is a huge improvement in terms of modularity, readibility and being more idiomatic:

The first step was to isolate in a new function the logic that performs the filtering on the sequence. I have created a `cuts` function on `line 1`. This improves the modularity.

The `process` function on line 5 uses the thread last macro. Both the thread macro `->` and the thread last macro `->>` make the code easier to read by allowing you to use an imperative style rather than nesting the calls. The thread last macro inserts the first argument that you pass to it as the last argument to each of the forms. Below are some simpler examples of the thread last macro that should illustrate how the argument fills in the last argument for each of the forms:

If we return to our example, we can use `macroexpand` to expand out the macro to its nested reality:

Below is the output of the `macroexpand` call:

The first argument in this case is supplied via the iterate function on `line 6` that generates an infinite lazy sequence by taking two parameters, a function and a seed value. The seed value in this case is the vector `[1 2 3 4 3 3 2 1]` and this is initially passed to the `cuts` function. `iterate` will then infinitely call `cuts` passing in as an argument, the previous call to `cuts`.

`map` is used to apply a function to each item returned from the `iterate` form and we use `count` as the function to transform the result of each call to `cuts`. `take-while` is used to constrain the infinite nature of `iterate` and as soon as the `pos?` function returns false, the results are returned to the calling function. We use `pos?` to check whether there are are any elements that are not zero. `take-while` will also accumulate the `count` results and return them to the calling function instead of using an accumulator argument like I used in my original example.

I really like how this turned out and it is definitely more idiomatic clojure than my original version and I think this is a good barrier to get past in my journey into clojure.

# Emberjs - Computed Properties and Promises…..don’t

A question I see coming up time and time again is how to return a resolved promise from a computed property.

There are a number of ways of doing this and I, like many have tried to solve this problem myself before realising that it is not a path you should go down.

I can flesh this out with an example that I originally solved using a computed property that resolved a promise.

I inherited a nasty bit of code on the server or API side of the project that I was working on that stored the relationship of different types af object in a generic postgres database column that used serialized yaml as the format to compound the uselessness. This is particularly wrong for a number of reasons such as you can’t query the sucker unless you use regular expressions. It is completely unmaintainable and you should never, ever do this and Edgar F. Codd who gave us relational database theory would be turning in his grave.

An example where this was used is in a user’s activity feed that contains audited events for a user of the application. For example if the user or contact sent an email then their activity feed would contain an item like this:

The `meta` field on `line 7` comes from the serialized yaml column and is used as a generic bucket that can contain different types of relationships or other junk, making it extremely difficult to work with. The answer to how to deal with this is refactor the server code and never, ever use serialized YAML but if you are stuck with this type of nonsense then how would you satisfy the `email` property of the template below? We need to somehow or somewhere load the email instance from the `meta.email_id` property.

When I first encountered this problem, my answer was to use a computed property that resolved a promise and then set itself:

On `line 11` of the above, I set the property when the property resolves.

This will more or less work and here is a jsbin that shows an example of how to do this.

There are a number of things wrong with this approach, namely we are trying to treat something that is inherently synchronous in an asynchronous manner. The cp will fire a number of times due to the promise resolving and I have had a lot of pain with ember and observing dependent keys. This can lead to the property referencing a partially resolved object or you can get cascading events on other cps and observers that reference a key firing in a sometimes recursive manner. These are situations I now avoid like the plague and if you have any sense, you will heed my battle weary tone and avoid them too.

I’ve also seen computed properties that reference promise objects or have dependent keys on the state of the promise, but that is far too contrived to be credible and will lead to pain. You will have partially resolved data and cascading events triggered. Don’t do this.

I develop with ember a lot different now than I did this time 12 months ago.

If you feel you need a computed property that will resolve a promise and you have read this, the answer is…….DON’T.

So what do we do?

Subscribing to data events throughout your application by using observers or waiting for computed property keys to update and trigger actions creates overhead but more importantly makes your application difficult to reason about and in my experience causes unreliable and inconsistent behaviour for reasons I have been writing about for a while now.

When data is passed from above rather than being subscribed to, we can react only when we know something has changed. React’s flux has popularised the top down approach and it makes nothing but sense.

So the answer is to let the resolved property be passed in from above in a top down fashion rather than listening for it to happen. Ember is on board with this philosophy and it goes by the meme data up and actions down although I think this could do with some better fleshing out.

So the first refactoring is to create a service that will be charged with resolving the `activity` instance and taking care of unwrapping this horrible `meta` hash that can contain all kinds of junk. I want this encapsulated and ready to use anywhere in my code. With this in mind, I have created an `ActivityService` that is injected into all components through this `initializer`:

A scaled down version of the `ActivityService` is below that takes care of loading the activity and unpacking this now infamous `meta` field:

The above code returns a promise that when resolved, will return a simple hash rather than the resolved ember-data instance. I prefer not to bind or work directly with the ember-data instances and I discussed this the benefits of this in this post. I have created a simple `shallowCopy` extension to the `DS.Model` class that creates a shallow copy of the ember-data instance:

In the original example, I iterated over the user’s activities like this:

I will replace this with a component:

The `ActivityFeedComponent` creates an array of activity hashes by calling out to the `ActivityService` and only pushing the resolved instances onto the `activities` array when the service has done what it needs to do:

This will give me so many fewer problems than resolving the promise in a computed property as I did in the original example. I only push onto the `activities` array when the service has done what it needs to do. I am also working with copies of the ember-data instance which will curtail any unwanted side effects that I might encounter. I will sleep better with this code.

The `activity-feed` component’s template simply looks like this:

Here is a jsbin that brings it all together.

So my message is clear, don’t resolve promises in your computed properties, nor should you have dependent keys on `isFulfilled` as I see some advocating.

You have been warned.

# Emberjs - Avoiding Side Effects…. Or at Least Trying

I’ve been using ember for 2+ years and the more I deal with a single page application that exists in memory for an indeterminate length of time, the more tenets of functional programming I embrace to bring some sanity to the chaos. The problem with ember is that it is more class or object based than functional.

The move to ember 2.0 will see ember become more functional but I think it needs to go further and drop a lot of the class based paradigms to make it more robust.

I’ll quickly run through the important tenets that could make your code more robust if you can employ them:

### Function Purity

You should always strive to make your functions as pure or side effect free as possible. Wikipedia gives the following definition for a pure function:

A pure function is a function where the return value is only determined by its input values, without observable side effects

Another way of expressing the above is that a pure function will always return the same value when given the same arguments.

Below is the most basic of basic examples of a pure function

This function is pure because it will always return the same result, given the same input. It only reads local variables and it only writes to local variables. This is also sometimes referred to as referential tranparency because the expression can be changed with its value without effecting the behaviour of a program. For example if we used the `addOne` function like this:

We can replace the expression with its value and still get the same result:

A simple example of an impure function is below:

The side effect of this function is that it changes the value of the `number` variable each time it is executed. The example above is not referentially transparent because if we call `sideEffect` with 3 we would get a different result each time.

On the surface dealing with only pure functions is very limiting, we would need to avoid things like `new Date` or `Math.Rand` because they always return a different value. `console.log` is also on the banned list because it accesses a global variable. In fact, any function that takes an object as an argument is potentially subject to impurity. The DOM is one big huge stateful side effect waiting to happen.

The bottom line is that if you are dealing with javascript, you will always be dealing with some degree of impurity or our programs would not be very useful. What we need to do is try and minimize this.

Ember’s Handelbars helpers can be pure functions but I have seen an RFC recently that wants to add all sorts of state and life cycle events which is something that made me shudder. I worry that if this rfc is pushed through then it will complicate something that is very useful and can be side effect free.

#### Purity and Idempotence

Idempotence entered the vernacular or at least resurfaced when REST went mainstream. An idempotent operation is one that has no additional effect if it is called more than once with the same input parameters. For example moving an item from a set can be considered an idempotent operation or deleting a record by GUID is idempotent becuase the row stays deleted.

Purity and idempotence are completely orthogonal, a pure function does not have to be orthogonal and vice versa. An idempotent function can cause idempotent side effects, a pure function cannot.

#### Immutability

In functional prograaming, the ideal situation is that there is never mutation. I blogged previously about some of the benefits of immutability and gave an example of how it might be used.

One of the traps I fell down when I first started developing with ember was to observe changes on mutable arrays like this.

I see this type of code in a lot of stackoverflow answers and blog posts but I now consider this to be an antipattern. Two way databinding was one of the things that first drew me to ember but ended up causing me no end of pain. I think two way databinding still has its place for binding simple literals like an input’s value attribute to a string prop of a value but binding object to object causes pain. I believe in ember 2.0, binding will be one way only by default and this is the right move. You can stop this now by ensuring you use `Ember.computed.oneWay` instead of `Ember.computed.alias`.

### Update

As Charles Lowell rightly pointed out in the comments, it is possible to create `readonly` computed properties that will raise an exception if a `set` is an attempted.

I’ll certainly be using this from now on.

One of the benefits of immutability is that diffing is done by value and not by reference, just think how easier diffing javascript would be if the following was true out of the box:

Libraries like om in clojurescript use diffing on their immutable datastructures to great effect to negate needless re-renders with reacts virtual DOM.

But the main reason that I am starting to see the main use case for immutability is that, it makes your code much easier to reason about and you can avoid side effects using immutable data structures. For me, the biggest thing about using immutable data structures is that I am completely safe from some unkown mutation happening which in a long running single page application is great for my peace of mind. I’ve been surprised too many times in the past.

You don’t have to use a library like seamless-immutable but you should try and tranfrom or create new objects or arrays rather than mutating existing objects. You should favour `map` or `filter` over `forEach`, `forEach` must have a side effect somewhere to accomplish anything. The only time I would use `forEach` is for something like this:

#### Statelessness

Imperative programming works by changing programming state to produce answers. Conversely, functional programming produces answers through stateless operations.

A good example of the contrast is looping, an imperative approach is to use looping:

The loop produces its results by constantly changing the value of `x`. A functional approach would use recursion:

Functional programming requires us to write stateless expressions and keep our data immutable.

### Back to The Real World……and Ember

If you perform a google for functional javascript you will get plenty of examples of sorting lists or simple number crunching. I have found very little about how to use functional techniques for the type of situations you face on a day to day basis as a web dev or your ongoing battle with the DOM. So I am going to use a real world example that I worked on within the last week of writing this blog post.

The last thing I worked on was a custom query builder where the user builds a query on the fly from the html elements he is presented with. Query items can be added and removed: If I had attempted something like this 12 months ago, I would have used rampant mutation, observers and two way binding in a huge chaotic side effect soup. I have my battle scars and I see the world differently. I will now detail my solution. I have created this jsbin that you can play along at home with and is a pretty damn accurate duplicate of how I solved this.

The truth of the matter is that ember is very, very, very stateful and adheres more to a class or object based methodology. If you want to reference data structures in your templates then you need to create member properties and reference them.

My goal for any new piece of code that I create is to keep things as side effect free as possible. I will most definitely never use the `Ember.observer` primitive, I use few computed properties if any and rarely use two way databinding. I will work with immutable copies of anything persistable. I want to keep surprises to a minimum and I want to keep things in my control and not be working or waiting for the run loop which is outside of my control.

In this custom query example, there is only ever one active query that you are manipulating, you are either building a new one or you are updating an existing query. These queries are persistable and I have modelled it as a parent query that contains a child collection of query parts. Here is the ember data CustomQuery definition:

And here is the queryPart:

My main goal for working with instances of these ember-data models is to not work with them. I am going to create copies of the data structure and work with those and only copy them back into the models when I want to persist anything. The last thing I am going to do is to use two way databinding to bind directly to the model properties. I have been down that path and it is the road to hell.

At any one time, we are dealing with a collection of query parts and we have query-builder component to add and remove query parts. Below is a screenshot of how the elements look:

The `IndexRoute` in the jsbin, either creates an empty array and assigns it to a `queryParts` variable that is passed to a `query-builder` component, or if we are dealing with a persisted query from the models above then we create a raw hash to pass to the component:

The user can navigate to the `IndexRoute` via a link that will have the custom query id in the query params that you can see on `line 5` of the above code. I am creating a hash rather than using the ember-data model directly to keep things side effect free. I have already made my life much easier.

Here is the how query-builder component is referenced on the parent template or the index template in the jsbin. The binding of the `queryParts` that are passed into `query-builder` are sadly still two way bound at this time of writing with `ember 1.11.1` but we will work with them as if they were one way bound.

Below is the template for `query-part.hbs`:

On lines `2 to 4`, a `query-part` component is rendered for each part of the query. The template for `query-part.hbs` is below:

The `query-part` component will fire off queries in response to either user input in the textbox or changing the query part operator in the dropdown.

Below is the code for the `query-part` component

We want to adhere to data down and actions up. So queries are bubbled up from this component to the controller.

If input is entered into the text input, the `keyDown` handler on `line 35` calls `sendQuery` on `line 12` that will `debounce` a call to `executeQuery`.

The code in `executeQuery` on lines `15-34`, could definitely be accused of being more jQuery than ember. If that is the case, then I am guilty as charged. I am using simple selectors to extract the values from the element rather than relying on two way databinding. I don’t want any surprises about values not being sync’d, I just want to extract the values from the elements when the query is run. There really is no need for it to be any more complicated than that.

I then bubble the newly constructred immutable data structure up to the parent component by calling the `modifyQuery` action. I don’t necessarily need these structures to be immutable but I want to guard against any side effects I might encounter unexpectedly. This action is then bubbled up to the controller where a it uses the raw hash to execute a `findQuery` on the main data that the query is filtering:

When it comes to saving the query, the `query-builder` component calls a `saveCustomQuery` action on the parent controller, passing the raw array of query parts which are plain old javascript objects and either creates a brand new `CustomQuery` model and persists it or overrides the existing `queryParts` collection of the existing instance:

There are only 2 parts in this piece of functionality where I deal with the actual ember-data instances. The first is when I am creating copies of the structures to feed to the components and here when I am persisting the changes back to the server.

### Epilogue

Congratulations if you made it this far, this is a long post. Staying side effect free and dealing with pure functions is next to impossible when working with something as stateful as the DOM. Ember also is very stateful and class based. I’ve used a real world example because there is no better example to illustrate just how challenging it is. I have 100% failed on the pure function front. But I’ve tried to stay as side effect free which for me means dealing with copies of anything persistable, avoiding observers, computed properties and two way data binding wherever possible. I’ve tried the other way and it is not pretty. The code I’ve described will give me a lot less headaches than other ways I might approach this.

I’m interested to see if we can take a much more functional approach with ember 2.0 but the rfc that wants to pollute handlebars helpers with state and life cycle events is not a step in the right direction.

I’ve heard of the benefits of functional programming for years but I now realise how sensible they are and how they lead to more robust code. When working in the chaotic world of the single page application, they make nothing but sense.

I would love any feedback at all on this. Good or bad, state your case.

# Emberjs - fillIn Test Helper With Key Events

I’ve imposed a self enforced ban on using observers when using ember. For example, I previously used two way binding in my template to bind the value attribute of an input element to a property

I would then create an observer on this bound value like this:

This has generally led to a world of pain that I lamented about in this post.

What I do now in this situation is use something like the input DOM event:

I can do any transformations in this event handler without the pain of obsevers or 2 way binding, I am in control of what is happening.

This is all well and good but what is not good is that this is not testable with the current ember test helpers.

There is the `fillIn` test helper but this will just set the value of an input to the supplied string without raising any key events:

What I needed was a way for the appropriate key events to be raised after every character. I might also have code in `keydown` and `keyup` for example.

With this in mind, I created this test helper to meet my requirements:

The above helper will input the text one character at a time and raise any supplied events.

For example if I only want to raise an `input` event with each character then I would use it like this:

Or if I want to raise more than one event then I can supply an array of input events:

You can use the helper like this in an `ember-cli` `test-helper` and I have created this pull request to get it included with the ember source.

# Emberjs - Action Maker

I am currently working on an ember project using `1.7.1` and I’ve reached the point of no return with regard to passing action names down a component hierarchy and then bubbling them back up using `sendAction`. I believe the problem is still present in recent versions of ember and we need to somehow make this more user friendly.

I will illustrate the problem with an easily grokked todo example before giving a couple of solutions.

Here is a list of todos:

Here I am creating a `todo-list` component and specifying an action that I want called when a todo is checked to signify it is finished.

Below is a route with a `finishTodo` action that is referenced in the above code sample:

All good so far but with the current state of data down and actions up, I need to pass this action name down to each child component that would use `sendAction` to call it.

In the example, I need to specify the action name in each `todo-item` component that the `todo-list` component creates:

I then need to bubble this up from the child `todo-item` component:

This gets bubbled up to the `todo-list` component that uses `sendAction` to bubble this up to the route:

Here is a jsbin that shows the up and down duplicity in its entirety.

One sure sign of tight coupling is the number of places/files that you need to change for one method name change. As developers, we should be seeing this type of thing as a red flag that requires attention.

One way round this is to create a helper to package up the action, the context and any arguments that are needed to call the action. This can be achieved with a handlebars subexpression and a handlebars helper.

I can refactor the `todo-list` component to this:

The above code uses a handlebars subexpression to create a method named `action` on each `todo-item` component, I pass in the `targetObject` which in this case is the `controller` but you can reference anything that is accessible and has an actions hash, I also pass the action name I want called and any additional arguments.

The subexpression calls this handlebars helper that returns a higher order function:

I can then call this action in the `todo-item` component:

Here is a jsbin of the above.

This makes things a little more sane for me and I can eliminate a lot of code. Another alternative that I am considering is to enhance the global event bus I previously blogged about.

The alternative is to carry on with what is currently on offer but I’ve just reached my limit with that.

# Emberjs - Simple Global Event Bus

Following on from my last post about Communication Between Components, somebody rightly pointed out in the comments that another way of doing this is to create a global event bus as a service and inject it into any components that need it.

I mentioned in my last post that the requirements are for the publisher and subscriber of events to know nothing about each other. A global event bus fits this bill. A global event bus, allows publish/subscribe communication between components without requiring the components to explicitly register with one another (and thus be aware of each other).

I think this will give us the quickest win for the stated requirements and we can quickly cobble together an Ember.Service that will act as an event bus using Ember.Evented:

An initializer is created to inject the event bus as a singleton into anything that might use it:

Now a parent component can pubish events using the injected `EventBus`

Child components can now subscribe and unsubscribe to these events without referencing the parent component:

I think this is the quickest path to market right now as it requires little effort. Subscribing to events based on a string literal is less than ideal but this fits my purpose of being outside the bounds of data down and actions up where no data has changed and the publisher and subscriber don’t know anything about each other.

Here is a jsbin that puts it all together.

I am very open to somebody pointing out a better way.