The optimal grid for any number of items

Recently I worked on a feature where I had to generate an image sprite for a number of equally sized images. Even though you can simply put all of these images below each other, I found it a challenge to generate an image sprite that was as closest to a square and with as little white-spacing as possible. What I ended up with is a function that calculates the optimal size of the grid (columns and rows) for any number of items.

An easy solution would be for 25 items: you’ll get an image sprite of 5 columns and 5 rows.

A grid of 25 items with 5 columns and 5 rows

It becomes harder if you look at 19: the only solution without white-spaces is a sheet of 19 columns and 1 row.

A grid of 19 items with 19 columns and 1 row

But if you want the result to be as square as possible you would end up with 5 columns and 4 rows, leaving you with 1 white-space.

A grid of 19 items with 5 columns and 4 rows

I wrote a function that calculates the optimal square-like grid size for any number of items. Additionally you can pass the minimum ratio you want; the function will loosen the threshold of white-spaces every time no grid can be created with a ratio above it.


Date range calculations

It happens once in a while that I come across a web-form that asks for 2 dates to indicate a time span. I know it can give quite an amount of trouble to program such a date range, especially due to validation. Luckily there can be tons of packages found on GitHub for frameworks like jQuery or AngularJS. What I didn’t found was a simple data type, so without any form of presentation, to handle and validate those ranges.

Recently I had to work with time spans that were not to overlap with each other and had to be subjected to all kinds of calculations. This inspired me to create a value object for it. Beware, the DateRange object.


This package is available via Bower:



Creating a date range is as easy as creating any object. When the passed dates do not form a valid range pair an error will be thrown.

This object can now give you any info about the range you like.

Calculating with a date range

Now, especially when the validation of you date range depends on other dates or ranges, some of the next methods might be useful to achieve this.


Full documentation can be found on GitHub.

Issues can also be filed there.

JS Value Objects – 4. Equality

Until now we learned how to create a Value Object. But we’ve seen that 2 instances of the same value object created with the same value do not equal each other. How can we make sure that their equality is based on value instead of identity? Let’s take a more practical example!

Note: This is the fourth post in a series about the use of Value Objects in JavaScript.

Registration form

We are going to build a very simple registration form with an email field and two password fields. When the user submits the form we want to validate the input before posting it to the server. When validation fails we prevent the post and show the validation error to the user.

The HTML might look something like this:

And the JavaScript like this:

In the validation part we need to verify that all fields are filled, that the email address is valid, that the password is strong enough and that the second password matches the first one. We will do this by first creating a Value Object for both email address and password.

EmailAddress and Password

We define EmailAddress in the same way as Integer in the previous post.

There is not much to it really. The only thing that makes the difference is the validation part. In this case we use a simple regular expression that tests the passed value for an @ and a dot with some other characters around it, but of course, you can make the regex as strict as you want. If the test fails we throw an exception stating that the value is not a valid email address.

Extra methods could be added to the object to access specific parts of the email address like the local part (before the @) and the domain part (after the @).

Passwords have to be strong, so they cant be easily guessed. In this example we define strong as ‘containing at least 8 characters and including at least 1 lowercase character, 1 uppercase character and 1 digit’.

Form validation

Validation is pretty simple now. We only have to create nwe instances of the defined Value Objects with the provided form input and all will be done automatically. The only thing we have to do ‘manually’ is checking if the two passwords are the same.

Sadly, we can’t compare the password objects directly because objects are always unique. Instead we have to compare the values of the those objects. Although it isn’t the worst thing you could think off, it still looks and feels a bit weird. If we compare strings or numbers with each other we do not need to access its inner value (we actually need to if we create them from their objects instead of from literals).

But is there no way to fix this? Yes, there is!

Equality with the flyweight pattern

The Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance. It will try to reuse already existing similar objects by storing them and creates new object when no matching object is found.

To simplify: Instead of creating 3 exactly the same objects only one instance is created and that one is referenced 3 times. Its works like a caching system. Of course this pattern has clear limitations. The main downside is that, if one of the references is changed, the original cached object is changed and therefor all references. So it is important that the object is immutable. Doesn’t sound that familiar?

Let’s build one for our Password VO. We start with the factory, the distributor of the flyweight objects.

Simple as that! Instead of instantiating the password our self we let it be created by the factory. It will first check if it has created a password with the same value before, if so he returns it, if not he creates it, stores it and returns it.

We reached our goal: Value Objects being equal on value.


Creating passwords like this doesn’t make beautiful code, but praise JavaScript for being awesome! We can rebuild the Password constructor to make it implement this pattern.

Defining the Password is now done inside a private scope to prevent variable name collisions, might you want to apply this pattern for more Value Objects (which you do, but more about that in the next post). The password constructor is now actually the flyweight factory that makes use of a private constructor defining the password. This gives us the ability to compare passwords that are created through pure instantiation.

I am really exited about this! As you see in the example, we actually beat the native data type objects, because they are not equal on value.

Back to our form validation we can now compare the two passwords without the need to access the value property of both objects.


We saw how Value Objects can be implemented in real life development with a practical example. Value Objects make validation easier and more readable, because they have high cohesion; everything about an email address is inside the object EmailAddress. There is no need to put any logic concerning the email address in the validation function.

A big improvement is the implementation of the Flyweight pattern that allows us to compare objects based on their value instead of their identity. This also makes our objects comply with the second key-property of values: ‘no life cycle’ (see post 2 in this series). Value Objects are no longer created (technically they are created the first time), but instead are references to an instance in the ‘universe of values’.

It is time to put all our discoveries together and create a library that helps us to generate our own Value Objects. To be continued…

JS Value Objects – 3. Integer data type

Note: This is the third post in a series about the use of Value Objects in JavaScript.

In the previous posts we introduced ourselfs to the concept of the Value Object design pattern and the way JavaScript implements data types (or value types) In this post we will start building our own value object in JS: the integer.

Reverse engeneering

Now let’s try if we can create an object that behaves the same way as the String object we inspected in the previous post.

We create a constructor called MyString, accepting a value, and give it the method valueOf in its prototype. The valueOf method is in fact overwriting the default one defined in Object.prototype, which all objects inherit from. This method is called whenever JavaScript tries to perform a binary operation on an object. For example when comparing (==) or joining (+) strings. Now lets run the same tests again on this new object:

So far, so good. We have similar results for these tests. But let’s be honest, we did not recreate the String object and that’s also not what we want to achieve. What we did do, is getting to know how you might create your own data types, or Value Objects.

Integer data type

An interesting thing about JavaScript is that it does not have an Integer data type. It has Number, representing all numerical values, but if we want to be sure that there is no fractional component we need to check it whenever we need to. To make our lives easier we will create our own Integer object instead:

This Value Object embodies the new data type: Integer. It can not be instantiated with an invalid value (we still want the value to be a number) and it can, because of the valueOf method, still be used in calculations:

When you instantiate a new String, Boolean, Number, etc without passing an argument, the object will get a default value (respectively “”, false, 0). This might not always be necessary, but lets say in our case it is preferable.

Note: To check if the value was passed you might be used to check if the value is falsable (but of course the passed value might be 0) or check if value is strictly equal to undefined, but that would mean you can not instantiate an Integer with undefined. I don’t know if you would be needing to, but still, this is the most valid way to check if really no argument was passed.

Parsing input

Another thing noticeable is that all native data type objects will never fail on no matter what input you would pass them.

String will always try to cast the input to a string which, in the worst case, will lead to “[object Object]”-like values, a Number will use the value NaN (Not a Number) whenever it can’t handle the input, a Boolean can cast all types of input, because if it is not falseable it is true and an Array will take its arguments as items in its list (just like the literal version []).

The Object-object treats its input with even more care. When you pass a string as a value it will create a string for you and returns the same result as you would get when creating a string with the String-object. The same counts for Number, Boolean, Array and even RegExp. In fact, if you pass it an object it will just return it back untouched.

In our case we would also like to be able to pass a value as a string. Maybe not as part of a sentence (like you would do with parseInt), but a value like “3” or “-12” should be possible. Beside that, it would also be nice if it would round a float to an integer.

When we multiply the value by one, JavaScript will first try to cast the value to a number and then multiply it by 1, resulting in either a valid number or NaN. When trying to round NaN to the nearest whole number the value will stay NaN, which will trow an exception on validation.


But wait! We can still change the value of the object!

We said in the first post that values have to be immutable. Values do not change, they simply get assigned to variables and removed if another value is assigned. Luckily JS provides us a way to assign properties in a way that they can not be changed.


Objects can have methods. Those functions can help us to interact with the value. The String object for instance has a method called toUppercase which will return a new all uppercase string of the original value. It is important to understand that this produces a new string and does not change the original string, because value objects are immutable.

In our case we might want to have a toFixed method that will produce a string created from the original value with a fixed number of decimals. Methods can be created on the prototype object, just like the valueOf function.

This will let us do whatever we want, but we have to keep ourselfs in control by making sure we doe not change the value itself.

The method in this example already exists on the Number object with exactly the same purpose. An integer and number (float) are much alike actaully, so why dont we just copy all methods in the Number prototype to the Integer prototype? Well, we cannot just copy paste as-is because the methods probably expect a certain internal structure and behaviour that is different in the Integer object. Instead we have to call the methods on the actual value by wrapping them into function.


Hurray! We created our first value object! By taking the Integer as an example we saw how a constructor can be used and tweaked to create an object that can pass as a value object. An object that is immutable and, as long as its value is not an object itself, cannot be referenced.

There is only one important part missing: The life cycle. Integers with the same value are not equal to each other, because both are objects and objects are unique.

In the next post we will take a closer look to this problem and I will write some more practical examples.

JS Value Objects – 2. Data types

Note: This is the second post in a series about the use of Value Objects in JavaScript.

In the previous post we learned what a Value Object (VO) is and what kind of problems it can solve. Now we can start exploring the possibilities in JavaScript (JS) for creating a similar pattern. In this post we will start with a brief view at data types.

Literals vs. Objects

JS provides 6 different basic types of values: numbers, strings, Booleans, objects, functions and undefined values (null and undefined).

Those primitives, with the exception of null and undefined, can be created from literals or from a constructor. The difference between those two methods of instantiating is not only the syntax, but also the actual value that it will produce. When using the loose equality operator you might not see this, but when you would compare the different methods with strict equality you will see that the value created from the constructor is an object and not a string (or number or Boolean).

This is a minor downside, but you should use the strict equality operator with care anyway. Another side-effect is that creating strings as objects is slower than creating it from literals. In general I would advice to use the literal way as much as possible.

Of course this does not count for objects, because an object is always only equal to itself. I will leave the  data type ‘function’ out of this discussion because they have a very special, multifunctional role in JS.

Note: Arrays are also objects and therefor not a primitive data type in JS. You can check this by using unary ‘typeof’ keyword.

Are Data Types Value Objects?

In the previous post we came across the 4 key properties of a VO: single concept, no life cycle, immutable and can not be referenced. Do these rules apply to the JS primitive data types?

Single concept

This rule most certainly applies. Just as much as in any other programming language. At least, for string, number, Boolean, object and function. Null is a bit of a strange value because it actually means that there is no value set and undefined is in fact nothing at all; it is, if one could say so, a not found value.

No lifecycle

For this rule it cannot be said just as easily, because it would mean that there could be only one ‘instance’ of every value that a data type could have. That is partly true:

According to this, we can conclude that strings created from literals do apply to the no life cycle rule, but strings created from objects do not. They have some kind of unique identifier that makes each instance different from another instance with exactly the same value. This is important to notice, because it conflicts with the description Eric Evans gave us in the first post; this is even better described by Martin Fowler:

Value Objects … their notion of equality isn’t based on identity, instead two value objects are equal if all their fields are equal. – Martin Fowler

We can test that this is not true for objects:

Note: Interesting is that we can compare objects if we convert both of them to a JSON string. This has a lot of limitations though; The objects can not contain methods (functions) and the order of the properties should be exactly the same.


Immutability is also partly true for JS data types. As strings, numbers and Booleans cannot be mutated, objects can:

No refference

Another characteristic of objects is that they are always referenced and although it can give you a lot of headaches, this is actually one of the things that makes JS a special language. Referencing has a lot of benefits; it gives you a lot of freedom, but it also provides a door to hell where it causes nasty side-effects that are hard to trace back.

In the above example we see that John and Peter live in the same house, but when Peter moves and we try to change his address, we also change John’s address.


Taking this all into account, you could say that the literals for creating a string, number, boolean, null and undefined are real values, because they have the key properties. Object on the other hand is failing for at least 3 of the 4 rules, because you might also argue if object is even describing a single concept.

The funny part is that in the next post we will find out that we have to use objects to be able to create our own VOs. So stay tuned!

Further reading

JS Value Objects – 1. The Concept

This post is part of a series about the use of Value Objects in JavaScript.

The Value Object (VO) have been around for quite some time (in fact, Dirk Riehle and co wrote an article in 1999 about the use of VOs in Systems), but I did not see a lot of functional implementations in web development. And especially in JavaScript it never crossed my path. In this series of posts I will explore the use of this design pattern in the awesome langue we call JavaScript.

“An object that represents a descriptive aspect of the domain with no conceptual identity is called a VALUE OBJECT. VALUE OBJECTS are instantiated to represent elements of the design that we care about only for what they are, not who or which they are.” – Eric Evans

In this post I will try to explain the use of VOs. Why do we need it? I like to use examples and I will use PHP code in this post, because the language supports an easier implementation than JavaScript (and using JS would spoil the fun for the next posts).

We have a problem…

Our system has users and a user can only exist with an email-address. We model this by creating a class User that requires an argument email in the constructor.

This would work. We will be sure that an user will always have an email-address when it is stored, because it can not be instantiated without one. Creating a new user would look something like this:

But our product owner suddenly decides that a user needs a valid email-addresses (. This means our rule changes: A user can only exist with a valid email-address.

When a new user is created we will validate if it is passed a valid email-address, if not it will throw an exception making sure it can simply not exist without one. This gives us the advantage that whenever we want to interact with a User model in our system, we now for sure that the user is valid.

Note: In my opinion this way (validation during construction) is favored over validation during storage. Some might argue that you would want to create a User (e.g. from a form post) and then validate its properties from the model itself. I agree that you would want the model to describe the “rules of existence” (validation rules), but that also means the model should not be able to exist if they are not met. Because of that I would prefer validation in the constructor and an exception thrown when it fails.

But lets say we want to give the user the ability to change his email-address. This puts us in a difficult position because we need to validate the changed email-address again. But luckily we now DRY:

Going well so far, but our product owner wants a new feature in the system: Users can register their own company. A company has a name and (you guessed it!) an email-address. What to do with validation now? We can not simply copy the method setEmail to the Company class, because that’s bad coding. We could instead create a helper-class or a Validator service that does the job for us, but that would make everything only more complex and harder to read.

Value Object to the rescue!

We can see email-address as an abstraction; a single concept. We said before that a String describes any piece of text. In the same way an EmailAddress would describe a string that contains a valid email-address. We could model it in exact the same way as we did with our first User model:

We now say that an email-address is a value type. It needs a string that represents a valid email-address just as before. The only difference is that we only care about that; higher cohesion than this would be hard to achieve. We can now change the user model like this:

By type-hinting the email argument we make sure that this model can only work with a valid email-address, since invalid ones can not exist.

You probably saw that I added two extra methods to the EmailAddress class. These methods are meant to help us to interact with the object. Since the attribute email in the User class is no longer a string, we can not use it in the same way we did before. This is a slight disadvantage, but PHP gives us a bit of help with the __toString method. Whenever we would echo the email-address PHP will try to cast the object to a string using this method.

Now, when we create a new user we would do it like this:

We now have a bit more preparation work before we can create the user, but what we achieved was that we completely decoupled the email-address from the user. We completely isolated everything that makes an email-address valid; everything concerning this abstraction can now be found in one place. We can even add methods that help us with dealing with the value.

The World of Values

We have seen now how useful this pattern can be, but before we can start implementing this in JavaScript we need to know what a value actually is. How can it be defined?

A value has four key properties (from ‘Values in Object Systems’ – Dirk Riehle) .

  1. It describes a single concept.
  2. It has no life cycle.
  3. It is immutable.
  4. It can not be referenced.

Single concept

Primitive values like string and number are very abstract concepts. A string describes any piece of text and a number any number you might think of. Other examples of value types might be date, currency, age, gender, email, etc.

No Lifecycle

Even though you might think that a value is created, for example through instantiation (new String), a value does not ‘live’.

Let’s say it is Rachel’s birthday and she turned 17. Does this mean a new age of 17 is created? And does it mean that the age 16 is deleted? No, it is best to stop thinking about values as objects. A value is something that lives in a inaccessible “universe of values” and is simply assigned to one or more properties and variables.


A value cannot change. This might be a bit hard to grasp, but maybe an example helps you to understand why this is important.

Barry lives in Rotterdam, but he has to move to New York because he got a new job. His family would say that “his address changed” from Coolsingel 3 Rotterdam to Wallstreet 25 New York. But technically that is not true. The address in Rotterdam does not change at all, instead Barry gets a new address located in New York. It means that the property ‘address’ of object ‘Barry’ changed its value.

No Reference

This property distinguishes values from objects. There are no references to values, because they can not be shared between different owners. Another example:

Peter Smith goes to the same gym as Peter van Dyke. They have the same name (the same value), which was fun in the start, but it gets a bit confusing when either of their personal trainers starts calling them. So, to make an end to it, Peter Smith decides to change his name to John Smith. When they meet next week, Peter van Dyke is still called Peter and not suddenly John because Peter Smith changed his first name to John.

This point is strongly related to the fact that values are immutable, mentioned before. Another important point to take from this is that values are side-effect free. They do not change other things than themselves and they behave the same under all circumstances.


The Value Object is a very useful pattern to structure logic about a single concept in a high cohesive way. It allows you to define the rules of your data in a solid way, making it harder for corrupt data to exist. VOs are immutable and can not be referenced which prevents unwanted side-effects.

Now that we have seen the benefits of VOs we want to find out if and how we could implement this pattern in JavaScript applications. In the next post we will see how primitive value types in JavaScript work and how we could replicate these with our own custom one. We will mainly concern about what the language allows us to do and what not, answering the question if it is possible to build a pattern that meets the requirements (key properties) of a VO.

Further reading

As I said, I might have over simplified the concept a bit, so if you want to dig deeper into this you might want to take a look at some of these resources, they sure helped me:

JS Value Objects

In the ‘days of the web-application’ that we live in, more and more calculation is done in the browser, but the code is often not prepared for that. When performing form-validation it can still give you headaches to come up with a decent structure to minimize the redundancy but still keep it dynamic enough so it can handle unknown future changes.

In the upcoming months I hope to write a serie of posts about the use of the Value Object pattern in JavaScript. This will be an experimental journey were I will try to find a way to improve the maintainability and sustainability of JavaScript applications.

Off-DOM element dimension

It can be really frustrating; you want to know the height of an element, but it is not in the DOM yet. Since the element’s width and height depends on the styling, the measures can only be calculated on screen, in the DOM.

Size & Styling

Your best shot is adding the element to the body in a hidden state (visibility: hidden) or off-screen (position: absolute; left: -9999px;), get the width and height and remove it from the DOM. But sometimes the size of the element depends on the css of an ancestor element, like width: 100%;, which is not present in the body. Or better, you can also append the element to the eventual element, but only if that one exists and sometimes it doesn’t.


If it doesn’t, we could replicate it. We can make a structure that will ‘mimic’ the eventual structure that the elements dimension depends on. An example:

The size of the paragraph depends on the ancestor elements; when it is a child of a section with the class .column it will have a maximum width of 300px and, since it has a larger font-size than the default 12px, will be higher than outside of the column.

Now, lets replicate the ancestors. I use the jQuery css-parser I wrote to create the elements.

This function will replicate the family tree needed to get the proper dimensions and can be used as simple as this:

Ok, this only works if you now the chain of ancestors, but hey, even the web can’t be perfect…

Screen Orientation API

The Web Applications Working Group has published a Working Draft of The Screen Orientation API.

The Screen Orientation API provides the ability to read the screen orientation state, to be informed when this state changes, and to be able to lock the screen orientation to a specific state.

Probably the most interesting feature will be the lockOrientation() method, allowing the developer to force the page to be viewed in a specified orientation.

This Working Draft is an update on a previous version published in May 2012.