I wanted to create a cross domain cookie based on the current domain of a page and I was provided with a list of sub domains where this should apply. Interestingly, this list included the name ‘uk’ and ‘cn’ which are also root level domain names.
Here are some example domains:
Here is a list of sub domains which can be removed:
Extending the ArrayArrays seemed the obvious choice to me. The domain string can be split on the full stop to create an array and the list of safe sub domains to be removed is already an array. Taking the first example, I end up with the following two arrays:
Now I wish to remove any items in the subDomains which form domainNameParts and return this result.
The subtract function loops over the input and compares each element with each element in the mask array. If it finds a match, the array splice function will remove it. It stops before it reaches the end of the input array though, to avoid removing any of the top level domains. Otherwise my example would return keithbloom.co - useless.
I now have a working function which can be used to create the domain for my cookie:
In the example I use the array function join to re-build my string and append a leading period to it. (For cross domain cookies to work, they must start with a period).
I now have a more expressive way to create my domain:
The final statement fits on one line. More importantly though it is concise and reads like a sentence. Creating code which is readable is more maintainable.
One way to avoid this is to prefix a namespace to my function: