Logesh Paul

Designer, Coder, UX Expert

Reverse String Using Javascript

| Comments

There are certain ways you can reverse a string in Javascript, Some of them are effective & efficient, some of them are neat. Feel free to choose the one which fits your project needs.

1. Decrementing for-loop with concatenation

1
2
3
4
5
6
7
function reverse(s) {
  var reversedString = "";
  for(var i= s.length -1; i>=0; i--) {
    reversedString += s[i]; //reversedString = reversedString+s[i];
  }
  return reversedString;
}

The original way that I achieved the intended result was to use a decrementing for-loop that appended each character of the input to a new string in reverse order. I was able to access the parsed strings individual characters similar to the way you would reference an array’s items.

2. Incrementing/decrementing for-loop with two arrays

1
2
3
4
5
6
function reverse(s) {
  var o = [];
  for (var i = s.length - 1, j = 0; i >= 0; i--, j++)
    o[j] = s[i];
  return o.join('');
}

Another way I formed to reverse a string was to create an empty array and iterate over the length of the string with both incrementing/decrementing counters. The array position uses the incrementing counter where as the parsed in string uses the decrementing one. Finally the created array is joined into a single string and returned.

3. Incrementing for-loop with array pushing and charAt

1
2
3
4
5
6
function reverse(s) {
  var o = [];
  for (var i = 0, len = s.length; i <= len; i++)
    o.push(s.charAt(len - i));
  return o.join('');
}

The above example is a modification of the second example. Instead of using two counters however we use one incrementing value that gets deducted from the total length of the parsed in string. This calculated value determines the position of the next character to be pushed onto the new array (using the ‘push()’ function instead of ‘[]’). The other difference from the last example is that it uses the strings ‘charAt()’ method instead of its array capabilities.

4. In-built functions

1
2
3
function reverse(s) {
  return s.split('').reverse().join('');
}

This implementation takes advantage of the ‘reverse()’ method provided by the Array prototype. First it splits the string into a real array, then calls the ‘reverse()’ method and finally returns the joined array.

5. Decrementing while-loop with concatenation and substring

1
2
3
4
5
6
7
8
9
function reverse(s) {
  var i = s.length,
      o = '';
  while (i > 0) {
    o += s.substring(i - 1, i);
    i--;
  }
  return o;
}

Using a decrementing while-loop I was able to implement this method. Again harnessing concatenation, I was able to achieve the iteration through the string in a similar fashion to the for-loop used in the first two examples. I was then able to use the strings ‘substring()’ function to retrieve each desired character.

6. Single for-loop declaration with concatenation

1
2
3
4
function reverse(s) {
  for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
  return o;
}

This is most likely my favorite implementation, due to its unnecessary cryptic nature. Using only a single for-loops parameters, I was able to decrement through the parsed in string and concatenate each character to a new string to return.

7. Recursion with substring and charAt

1
2
3
function reverse(s) {
  return (s === '') ? '' : reverse(s.substr(1)) + s.charAt(0);
}

The above example recursively calls itself, passing in the inputted string, excluding the first character on each iteration, which is instead appended to the result. Iterating through this process until no input is present (the base case) results in a reversed string.

8. Internal function recursion

1
2
3
4
5
6
function reverse(s) {
  function rev(s, len, o) {
    return (len === 0) ? o : rev(s, --len, (o += s[len]));
  };
  return rev(s, s.length, '');
}

This is another example of using recursion to reverse a string. The implementation above uses an internal function, which is first called by the outer function, parsing in the inputted string, its length and an empty string. The internal function is then recursively called by itself until the string length has been decremented to zero - at which time the originally empty parsed in string has been concatenated with the inputted string characters in reverse.

9. Half-index switch for-loop

1
2
3
4
5
6
7
8
9
10
11
12
function reverse(s) {
  s = s.split('');
  var len = s.length,
      halfIndex = Math.floor(len / 2) - 1,
      tmp;
  for (var i = 0; i <= halfIndex; i++) {
    tmp = s[len - i - 1];
    s[len - i - 1] = s[i];
    s[i] = tmp;
  }
  return s.join('');
}

I found this method to be a very effective way of reversing a string, highlighting its benefits when processing large strings. The strings half-point is first calculated and then iterated over. Upon each iteration the upper half’s value (calculated by deducting the current position by the string length) is temporary stored and replaced by the lower half’s value. The temporary value then replaces the lower half’s value to finally result in a reversed string.

10. Half-index recursion

1
2
3
4
5
6
7
function reverse(s) {
  if (s.length < 2)
    return s;
  var halfIndex = Math.ceil(s.length / 2);
  return reverse(s.substr(halfIndex)) +
         reverse(s.substr(0, halfIndex));
}

The final method I wish to show uses the same ideology as the last implementation (half-indexing) but instead relies on recursion to reverse the string instead of a for-loop.

Demo

Demo Link

Advance CSS Selectors

| Comments

CSS is awesome cause it gives the visual appearance to your website, I can’t think of website without css.

Often we use simple id or class for an element to target styling. Sometimes there are scenarios where class names are dynamically generated, in those cases we will relay on JS to insert modifier classes just to bring some unique styles thats isn’t cool, The good thing is there are some useful selectors in css which can take care of it and save some lines of your JS-Just-Used-For-Styling.

In this post we will be looking at some advance css selectors to help with typical use cases.

Partial Selectors

Partial selectors useful if you want to target styles if you are aware of part of your classname

Here is a list of things we will be looking at

  • $= ends with
  • ^= begins with
  • *= contains

Ends With ($=)

Selecting an element with CSS that has a repetitive suffix would look like this:

1
2
3
div[id$=_myDiv] {
// cool CSS stuffs
}

The first thing to note is the div with the brackets surrounding the id$ attribute. The div tag can be any element in the DOM from input to span and so on. This is awesome if you’re trying to target a specific element that has a dynamic prefix like this:

1
2
3
<div id="0125_LoginPanel">
Some sample content
</div>

So to target this div just use the selector like before and write:

1
2
3
div[id$="_LoginPanel"] {
  padding: 1em;
}

You can do it for any element (div, span, img, etc…), and any common attribute (id, name, value, etc…).

Begins with (^=)

Much like the “ends with” section above you can target elements with specific prefixes. The only difference than before is what character you add to the selector following the = sign.

1
2
3
<div class="myPanel_1435">
  <h1>My custom panel</h1>
</div>

Then the selector would look like this:

1
2
3
div[class^="myPanel_"] {
  // cool CSS stuffs
}

Simple enough right? All we did that’s different than the ends with ($=) selector is target the prefix by adding a ^ symbol in front of the = sign. You may also notice this time I used a class instead of an id. CSS is flexible enough to pretty much let you target anything as I stated earlier.

Contains (*=)

What if your have both a dynamic prefix and suffix? Well, luckily you can target an element that simply contains a parameter.

1
2
3
4
<div class="1gdug_logoutPanel_4828fde">
  <h1>My Custom Logout Panel</h1>
  <form>...</form>
</div>

Targeting this could look like:

1
2
3
div[class*="logoutPanel"] {
  // cool CSS stuffs
}

So essentially any div that contains the text logoutPanel can be selected like the example above.

Pseudo-class selectors

Simply put, pseudo-class selectors are CSS selectors with a colon preceding them. Many of these are commonly used for links or interactive types of elements.

1
2
3
4
5
6
7
a:hover {}
a:active {}
a:focus {}
a:visited {}
:checked {}
:first-child {}
:last-child {}

I’m not going to cover these things, as you might be already aware. Like it’s mentioned on the post title we will look at some advance Pseudo-class.

:not(x)

Instead of putting on the border…

1
2
3
4
/* add border */
.nav li {
  border-right: 1px solid #666;
}

…and then taking it off the last element…

1
2
3
4
/* remove border */
.nav li:last-child {
  border-right: none;
}

use the :not() pseudo-class to only apply to the elements you want:

1
2
3
.nav li:not(:last-child) {
  border-right: 1px solid #666;
}

Sure, you can use .nav li + li or even .nav li:first-child ~ li, but with :not() the intent is very clear and the CSS selector defines the border the way a human would describe it.

::first-letter

Drop caps are pretty slick when it comes to reading and authoring content for the web. These were made famous with print and have now become a nice trend in the blogging world. With pseudo class selectors you can target the first letter of a paragraph or element by simply writing:

1
2
3
p::first-letter {
 // drop cap styles
}

You probably don’t want to target every paragraph so to work around this you can actually chain together pseudo selectors

1
2
3
p:first-child::first-letter {
 // drop cap styles for only the first paragraph of text.
}

This is so useful and saves you from having to use JavaScript or something more hacky to style up your content nicely.

:first-of-type

:first-of-type is one I use all the time which allows you to select the first of any type within the current parent element and target it via CSS.

1
2
3
article:first-of-type {
  margin-top: 0;
}

:last-of-type

You can’t have :first-of-type without :last-of-type. This selector works the opposite way of :first-of-type if you hadn’t already guessed.

1
2
3
4
article:last-of-type {
  border-bottom: none;
  margin-bottom: 0;
}

PS. Do share your favorite advance selectors in the comments section

Know Where You Are Going in Life

| Comments

A boat docked in a tiny Mexican fishing village. A tourist complimented the local fishermen on the quality of their fish and asked how long it took them to catch it.

“Not very long.” they answered in unison.

Why didn’t you stay out longer and catch more?

The fishermen explained that their small catches were sufficient to meet their needs and those of their families.

But what do you do with the rest of your time?

We sleep late, fish a little, play with our children, and take siestas with our wives. In the evenings, we go into the village to see our friends, have a few drinks, play the guitar, and sing few songs. We have a full life.

The tourist interrupted. I have an MBA from Harvard and I can help you! You should start by fishing longer every day. You can then sell the extra fish you catch. With the extra revenue, you can buy a bigger boat.

And after that?

With the extra money the larger boat will bring, you can buy a second one and a third one and so on until you have an entire fleet of trawlers. Instead of selling your fish to a middle man, you can then negotiate directly with the processing plants and may be open your own plant. You can then leave this little village and move to Mexico City, Los Angeles, or even New York City! From there you can direct your huge new enterprise.

How long would that take?

“Twenty, perhaps twenty-five years.” replied the tourist.

And after that?

Afterwards? Well my friend, that’s when it gets really interesting, answered the tourist, laughing. When your business gets really big, you can start buying and selling stocks and make millions.

Millions? Really? And after that? asked the fishermen.

After that you’ll be able to retire, live in a tiny village near the coast, Sleep late, play with your children, Catch a few fish, and take a siesta with your wife. And spend your evenings drinking and enjoying your friends.

With all due respect sir, but that’s exactly what we are doing now. So what’s the point wasting twenty-five years? asked Mexicans.

Know where you’re going in life… You may already be there!

How to Get Internet Explorer on Mac for Testing

| Comments

While developing web applications you want to test your application across browsers especially Internet Explorer/Edge. I have always been a fan of grabbing a spare PC and having IE tester or Install latest IE version and toggle between the modes.

After switching to Mac back in 2011 I don’t have a spare PC available so I evaluated the latest web-based options including BrowserStack and Sauce.

Both have a wide variety of platforms and browsers from which web applications can be tested. However, I was unable to reproduce some reported bugs and saw other bugs which weren’t reported. Both are fairly slow to boot up and navigate in the browser. In order to test them locally, you need to set up a web tunnel either through command line tools or through each of their interfaces.

After exhausting the web options, I decided to explore Virtual Machines (VMs) as browser testing environments. Setting up a VM was a pretty simple three step process:

  1. Download Virtualbox and install.
  2. Install the IEVMs you need- More Instructions
  3. Wait for some time. Depending on your internet connection it can take a while.

The install script sets up every version of IE back to v6, which hopefully I’ll never have to use. Each VM is pretty quick to start up (e.g. X seconds) and easy for local testing. Overall, VMs have been a pleasant surprise, compared to hosted solutions and the extra PC.

Time to smash those CSS bugs in IE.

Javascript - Types

| Comments

Differences between undefined and null

  • undefined means a variable has not been declared, or has been declared but has not yet been assigned a value
  • null is an assignment value that means “no value”
  • Javascript sets unassigned variables with a default value of undefined
  • Javascript never sets a value to null. It is used by programmers to indicate that a var has no value.
  • undefined is not valid in JSON while null is
  • undefined typeof is undefined
  • null typeof is an object. Why?
  • Both are primitives
  • Both are falsy (Boolean(undefined) // false, Boolean(null) // false)

You can know if a variable is undefined

1
typeof variable === "undefined"

You can check if a variable is null

1
variable === null

The equality operator considers them equal, but the identity doesn’t

1
2
3
4
// equality
null == undefined // true
// identity
null === undefined // false