Quote


A good programmer is a lazy programmer, because he writes minimum code.
--Anonymous


Thursday, February 15, 2018

JavaScript Tips and Tricks 1: Sorting Array

As part of my computer engineering course, I wrote algorithms to sort array in different programming languages like Fortran, Pascal and even in C. We all did in our college days. However, as part of job, did you ever have to write such a program? I think no, because all modern languages provide built in functionality to sort.

JavaScript is not different. It has the sort function, which we can use whenever we need to sort an array. In this blog post, we will examine how JavaScript sort can be used in different scenarios.

Sorting One Dimensional String Array

Sorting an array in JavaScript is kid's play, provided the array is a one dimensional string array. If not? well, even if it is not one dimensional string array, it is not that difficult.

Then, let's start with one dimensional string array. Sort method of the Array prototype is handy here. See the below code.

var arr = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog"];
arr.sort();
console.log("Sorted array: " + arr);

// Sorted array: brown,dog,fox,jumps,lazy,over,quick,the


Sorting String Array in Descending Order

What if you want to compare in descending order? Unfortunately, there is no method to support in descending order sort, but no need to worry. The reverse method of array comes in handy here. Apparently, you can sort in ascending order and then reverse the array to do sort in descending order.

var arr = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog"];
arr.sort();
arr.reverse();
console.log("Sorted array: " + arr);

// Sorted array: the,quick,over,lazy,jumps,fox,dog,brown

Sorting Case Insensitive

Again, sort is case sensitive. What if you want a case insensitive sort? Sort function accepts a compare function, which is of great help.

var arr = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "Dog"];
arr.sort(function(s1, s2) {return s1.toLowerCase().localeCompare(s2.toLowerCase())});
console.log("Sorted array: " + arr);

// Sorted array: brown,Dog,fox,jumps,lazy,over,quick,the

Of course, you can use the shorter syntax for function declaration for brevity.

var arr = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "Dog"];
arr.sort((s1, s2) => s1.toLowerCase().localeCompare(s2.toLowerCase()));
console.log("Sorted array: " + arr);

// Sorted array: brown,dog,fox,jumps,lazy,over,quick,the

That's all about string array sort.

Sorting Numerical Arrays

Now let's see how we can sort numerical arrays. The sorting numerical array is not straight forward as string array sorting because of one reason. The Sort function by default considers the member elements as strings. So, if we sort a numerical array, the string sort will be happening, which will not give us the expected result. For example, 100 comes before 25, because the string "1" is bigger than "2". Solution? The compare function discussed in previous example again saves us.

var arr = [12, 0, 6, 22, 45];
arr.sort((n1, n2) => n1 - n2);
console.log("Sorted array: " + arr);

// Sorted array: 0,6,12,22,45

want it in descending order? Just change the second line.

arr.sort((n1, n2) => n2 - n1);

//Sorted array: 45,22,12,6,0

Sorting Array of Objects

Let's wind up by discussing the last point. Sorting an array of objects.

var arr = [{productId: 1000, productCode: 724123, productName: "Moto G5s Plus"},
{productId: 1001, productCode: 223426, productName: "Samsung On5"},
{productId: 1002, productCode: 523426, productName: "Apple iPhone 7 Plus"}];
arr.sort((item1, item2) => item1.productCode - item2.productCode);
console.log(JSON.stringify(arr));

// result:
// [{"productId":1001,"productCode":223426,"productName":"Samsung On5"},
// {"productId":1002,"productCode":523426,"productName":"Apple iPhone 7 Plus"},
// {"productId":1000,"productCode":724123,"productName":"Moto G5s Plus"}]

Probably, you should have got this, how to sort on a string key? For example, by productName in previous example? Yes, we can use the same method we used for case insensitive sort.

var arr = [{productId: 1000, productCode: 724123, productName: "Moto G5s Plus"},
{productId: 1001, productCode: 223426, productName: "Samsung On5"},
{productId: 1002, productCode: 523426, productName: "Apple iPhone 7 Plus"}];
arr.sort((item1, item2) => item1.productName.localeCompare(item2.productName));
console.log(JSON.stringify(arr));

// result:
// [{"productId":1002,"productCode":523426,"productName":"Apple iPhone 7 Plus"},
// {"productId":1000,"productCode":724123,"productName":"Moto G5s Plus"},
// {"productId":1001,"productCode":223426,"productName":"Samsung On5"}]

Monday, September 28, 2015

Queen Puzzle!


Friends,

I am back with a Queen Puzzle. My another adventure with AngularJs. Have fun!

Want to play with source code? Click here to download.

Working well in Chrome and FireFox, but IE seems messy.

Rules

Place Eight queens on the chess board in a non-attacking position
  • To place a queen in a square, click on a empty square
  • To remove a queen from a square, click on a queen on the board
  • To move a queen, first click on a queen to remove it, and then click on an empty square
8
7
6
5
4
3
2
1
a b c d e f g h

Congrats! You have won.


Wednesday, February 25, 2015

Multiplication Table with Angular JS

Hi Friends,

I was away for a long time. Many things happened in my technical life during this time. The biggest change is I moved to mobility. When I checked the viewer list today, I was astonished to see so many visitors to my blog. Overwhelmed by the feeling that I should give some thing back, I decided to post some thing.

What to post? Lately I was trying to familiarize with  Angular JS and decided to write some thing about. In order to familiarize with Angular JS, I did a multiplication table.

My six-year-old son liked it. So I thought at least children will like it.

I tried to publish the js in this page itself, but no luck. But you can download it from here.

Sunday, January 30, 2011

AutoCorrect Macro

Friends,

When you chat you type like this "how r u? c u tmro". But when we type an official mail, we have to switch to that bad old English that we were taught in schools. I observed that whenever I type an official document, I always type "ur" then hit backspace and correct it to "your". Then I thought, "Why should I assign this correcting job to my computer?" When I thought more about it, I decided to use AutoCorrect feature that comes with MS Office.

One advantage of Office AutoCorrect is that if you make an entry in one office application, it will be available in all office applications. That means if you customize AutoCorrect in MS Word, that will be available to MS Excel, Outlook, PowerPoint, etc.

So, I opened MS Excel and added a few entries there. Here are the steps to do this in MS Office 2007.
  1. Click the Microsoft Office Button, and then click Word Options.
  2. Click Proofing.
  3. Click AutoCorrect Options.
  4. On the AutoCorrect tab, click to select the Replace text as you type check box.
  5. Click OK to close the AutoCorrect Options dialog box.
  6. Click OK to close the Word Options dialog box.
I added a few entries like please for pls, you for u, your for ur. This simplified my typing a lot, and after some time this became some thing that I cannot live without.

Then I thought of sharing this with friends. I can email them the steps to do this, but I know my friends, they are not going to spend five minutes for this. So I created an excel macro to do this.

What I did is I type all the auto correct entries I wanted to add in the Excel sheet. I  also put a button in the first worksheet of an Excel file and set text to Add.



Then I assigned the macro Button1_Click to that button. Here is the code for Button1_Click.

Option Explicit

Sub Button1_Click()
    AddAutoCorrect
End Sub

Private Sub AddAutoCorrect()
    Dim intRow As Integer
    Dim intReplacementCount As Integer
    Dim sheetAutoCorrect As Worksheet
    
    intReplacementCount = 0
    intRow = 2
    Set sheetAutoCorrect = ActiveWorkbook.Sheets("AddAutoCorrect")
    
    Do While sheetAutoCorrect.Cells(intRow, 2) <> ""
        If sheetAutoCorrect.Cells(intRow, 2) <> "" And _
                    sheetAutoCorrect.Cells(intRow, 3) <> "" Then
            Application.AutoCorrect.AddReplacement sheetAutoCorrect.Cells(intRow, 2), _
                    sheetAutoCorrect.Cells(intRow, 3)
            
            intReplacementCount = intReplacementCount + 1
        End If
        
        intRow = intRow + 1
    Loop
    
    MsgBox intReplacementCount & " enties added to Office AutoCorrect."
End Sub

Now adding the auto correct entries is as easy clicking the add button.

If you are not ready to do even this, you can download the Excel file here.

Thanks,

Saturday, December 4, 2010

Creating Notepad++ Macro for HTML Tag Wrapper

I know lot of people using Notepad++ (NPP) for editing HTML and XML rather than Visual Studio, including me. Its color highlighting and outlining are better compared with Visual Studio even though NPP misses features like auto intending and auto completion of tags. However, the new features in VS 2010 are awesome. Probably, I will not use NPP for HTML editing any more.

Having said that one limitation with NPP is that it does not insert closing tags automatically. You have to type  the <, >, /> every thing by yourself. Whatever advantages HTML and XML have, no one said it is keyboard friendly. 

When I have to create some HTML, I found this is a big inconvenience. I quickly searched for a work around. I found macros are supported in NPP. The macros in NPP is much simple (and less sophisticated) than that in Office and Windows. It simply allows you to record key presses and you can play it back on demand.

Here is the steps to create an HTML tag wrapper macro in NPP.
  1. Open Notepad++ (I use version 5.4.3)
  2. Type some html tag, say html (without < and >) and double click on it to select it.
  3.  Now click on Macro menu, and click on Start Recording.
  4. Press these keys. CTRL+C, LEFT ARROW, <,  CTRL+RIGHT ARROW, >, <, /, CTRL+V, >, LEFT ARROW, CTRL+LEFT ARROW, LEFT ARROW.
  5. Click on Macro menu, and on Stop Recording.
  6. Now test this. Move to a new line and type in another html tag. for e.g. body. Now select it, and click on Macro, Play Back.See the <, > and closing tags are inserted.
  7. Save this macro by clicking on Save current recorded macro in Macro menu.Give a name to it, some thing like TagWrapper. Click OK. From experience I learned that the keyboard shortcut that you can add here starts recording only. So, don't bother about it time being.
  8. Now you can see the TagWrapper is added to the macro menu. See screen shot below. 
  9. Next time when you want to insert an html tag, do like this. Type in the tag name, like table, select it, and then click on Macro menu, and select TagWrapper.










By the way, if you want to edit HTML in NPP, first select the language as HTML. To do this, click on Language menu and select HTML.

Also, this macro clears the clipboard. See the Ctrl+C and Ctrl+V keys in the step 4.

Hope this helps some one. 

Thanks.

Saturday, October 30, 2010

Index - All Posts

  • JavaScript Tips and Tricks 1: Sorting Array
    As part of my computer engineering course, I wrote algorithms to sort array in different programming languages like Fortran, Pascal and even in C. We all did in our college days...
    Read More...

  • Queen Puzzle!
    I am back with a Queen Puzzle. My another adventure with AngularJs. Have fun! ...
    Read More...

  • Multiplication Table with Angular JS
    I was away for a long time. Many things happened in my technical life during this time. The biggest change is I moved to mobility. When I checked the viewer list today ...
    Read More...

  • AutoCorrect Macro
    When you chat you type like this "how r u? c u tmro". But when we type an official mail, we have to switch to that bad old English that we were taught in schools. I observed that whenever I type an official document, I always type "ur" then hit backspace and correct it to "your". Then I thought, "Why should I assign this correcting job to my computer?" ...
    Read More...

  • Creating Notepad++ Macro for HTML Tag Wrapper
    I know lot of people using Notepad++ (NPP) for editing HTML and XML rather than Visual Studio, including me. Its color highlighting and outlining is better compared with Visual Studio even though npp misses features like auto intending and auto completion of tags. However, the new features in VS 2010 are awesome. Probably...Read More...

  • Tips to Make Your Applications More User Friendly 
    User Experiece design is not kid's play. If you want to make your applications more user friendly, you need to put lot of effort and money. But, if you are just a developer, doing the UI design, here are some tips that can help you. Read More...

  • User Experience Lesson from Twitter
    I was tweeting on the other day, and amazed by a simple feature in Twitter. The simple design of Twitter is the best evidence that they are not trusting their programmers with User Experience (Ux) design. I believe they have a separate Ux team. Well, I got one more evidence today. Read More...

  • Puzzler!
    Did you notice the sliding puzzler in my blog at right hand side? If not, please scroll down and see. Try arranging the numbers from 1 to 15 consecutively. It is interesting time pass Read More...

  • Watch delayed live of Anand Topalov Game
    As an Indian, I am happy to hear Anand winning world chess championship (Don't speak about Cricket now). As the newspapers only wrote the overview of the game, I was eager to follow the game. Read More...

  • A Forwarded Email
    Some one forwarded me this image.Read More...

  • Singleton to Read Configuration
    When we first learned the basics of coding, we are told that simple code is the best code. We believed if for a long time, and went extra mile to make the code simpler. Then came the Design Patterns, the new excuse for making code complicated. Earlier we used two lines of code to instantiate an object, but now we are using four classes for the same purpose. Read More...

  • User Experience Lessons from My New Mobile
    User Experience design was my favorite topic for a long time. I am not sure when I fall in love with this topic. During initial years of my career I got lot of chances to design screens for Windows Applications. I was just imitating Windows at that time, and believe me, I got lot of appreciation. But now I realize it was a mistake...Read More...

  • Exception Handling Blunders
    When I do code review, one area I give at most care is the Exception Handling. There are two reasons for this...Read More...

  • Break when an exception
    The scenario is like this. You are debugging some code. From the code an exception is thrown. As the exception handlers are in place, you know the exception happened only when the flow reaches exception handler code. So, in order to find out the exact line of code, where the exception happened originally...Read More...

  • Visual Studio Code Snippets - Get Away from Highlighting
    Code Snippets are important productivity tool in Visual Studio.NET. Simply stated, code snippets are ready made code blocks, which you can use in your code. They can be accessed in Visual Studio either by right clicking in code editor and selecting Insert Snippet or by simply typing in the short cut for the snippet and ...Read More...

  • Minimize to save memory
    Does Minimizing a Windows application reduce memory usage? So says this blog. An interesting piece of information. "In any multitasking system, minimizing an application means that it won't be utilized by the user right now. Therefore, the OS automatically makes the application use virtual memory and keeps bare ...Read More...

  • Active Threads in a Thread Pool (How I solved a problem)
    I wanted to get number of threads active in the ThreadPool. Our client wants this to be logged. I thought it is walk on the park when I found the function ThreadPool.GetAvailableThreads. However, when I read more in MSDN, I found I was wrong...Read More...

  • My favorite freewares
    Here are my favorite freewares...Read More...

  • Microsoft Comes To Your Town
    Microsoft Community Techdays are back...Read More...

  • Microsoft Excel 2003 to Excel 2007 mapper
    Recently our company upgraded to Excel 2007 in all its machines. While we enjoyed the cool new look and features, it has a downside. People who were experts till yesterday, became novices today. Most of the time spent for searching menus or toolbar shortcuts, which we already know in Excel 2003...Read More...

  • Open source is bug free?
    I was thinking that Microsoft programs are buggy and open source programs are bug free, Until I read this blog by Steve Bellovin, one of the pioneers of Internet security...Read More...

  • Power Toys!!
    I don't remember exactly when I heard about Microsoft Power Toys for Windows XP. I remember it was during work. If I come across interesting links or freewares at work, I will forward those links to my personal email, so that I can try those at home. When I checked my email today I found the link to Power Toys... Read More...

  • Explore the World
    Explore the world, but lazily. Well, it is not the best name I can found out. I had a few other names in my list, but unfortunately all are already taken. But, I hope this describes me best. Lazy is one word hated very much in the IT world. Our favorite words are hard working, proactive, professional, talented, motivated, etc...Read More...

Tuesday, August 24, 2010

Tips to Make Your Applications More User Friendly

User Experiece design is not kid's play. If you want to make your applications more user friendly, you need to put lot of effort and money. But, if you are just a developer, doing the UI design, here are some tips that can help you.

1. Don't ask users what they want.

If some one from Microsoft comes to you and asks you "ok, we are going to develop next version of Windows. Could you please tell us what all new features you want?". Can you tell them the new features, you want? Well, you can give one or two suggestions, but not awesome features, which make you think that why don't Microsoft bring it earlier. Why can't you tell them? The answer is simple. You don't know what you want.

Then, how can you find out what users want? Watch what users are doing. It will give you much insight on what users want. Also, talk with them and try finding what are their goals.

2. Add a memory to your application

In Windows, click on Start, and then Run. The Run dialog box comes. What you see there? The last application you have run. Click on the drop down and see a list commands you entered in the past. Windows remembers not only the last command you have run, but also a list of commands you have entered so far. We see this in most of the applications, but developers normally forget to implement this in the applications they develop.



Most of the time users enter same value to a textbox in our application. So, if the application can remember what the user entered last time, it saves lot of key presses for the user.

Many Ux experts believe that this is the most powerful tool, that can make applications user friendly.

3. Use message boxes sparigly.

The easiest way to give feedback to the user is a message box. In web applications, this may be a littile difficult, still you can overcome it with Javascript. But remember easiest way may not be the best way.

What's wrong with message boxes? It breaks the flow and upsets the user. Why this message box has come? Did I do any thing wrong? Is my data lost? These are the questions that comes to users' mind. Simply a message box breaks the feel good factor of users.

When I say this to some one, I always have to answer this question. "I see message boxes in applications developed by Microsoft or even by Google. If it were so bad, why don't they avoid it?" The answer is there is a trade off. When they avoid a message box, it gives them more work. Some times they will go for it, some times they will just put a message box.

When I say message boxes it includes confirmation boxes also. By confirmation box, I mean the message box comes with a question. Typically, "Are you sure you want to do it?" kind of messages. It helps the users, if they clicked some where by mistakes, but it irritates then when they deliberately want to do it. "Yes, I am sure. That's why i clicked on this." may be a typical response.

Now, how can we avoid message boxes?
  1. Avoid message boxes to report normalcy. If you clicked on a Save button, and the application saves data, this is just normal. Avoid putting a message box to say "Your data is saved".
  2. What if user gives a bad command? Use your creativity to find out alternatives to message boxes. Remember no need to give a good output for a bad command. If the user gives right command, give good output. If the user gives bad command, give bad output. One exaple is from Internet Browsers. What happens when you enter a wrong URL? Then also it displays a page, which says some thing like "Address not found". It didn't throw a message box. If you give right URL, it displays the right page. Otherwise it displays wrong page. Fair, no?


  3. Another problem is when users give incomplete input. Users click the Submit button before entering all mandatory fields. In that case what we can do? One solution is assumme incomplete data. For example, say there is a country drop down in an application. In the drop down there is an "(All)" option, and also all countries in the world. If you select any country and click Submit, the data for that country will be shown. And if you select "(All)", it will show data for all countries. Now, what if the user doesn't select any thing in the drop down and click Submit? The application can safely fill "(All)" for the missing input and show the result. There is no need to show a message box here.
  4. Make ncorrect input impossible. Another problem is when users enter incorrect data. For example, if there is textbox user can enter the Gender. As it is a text box user can enter some invalid value here, which will force you to show a message box. Obviously in this case, the solution is to put a drop down or radio buttons instead of the text box.  
  5. How can we avoid confirmation boxes? Well, you need to warn users before they perform some critical task, like deleting all values from the database. What heppens if you simply allow them to delete? Yes, I agree we cannot get away with confirmation boxes completely. But there are cases when you can avoid it. I have seen one application which confirms every thing you do. When you click on a Save button, it will ask you "Are you sure to save it?" or if you click on Delete button, it asks "Are you sure you want to delete?" likeways. One problem with this approach is confirmation boxes work only if they happens occassionally and unexpected. If the user expects it, she will just click Yes or No, without even reading the contents. But it helps if it is unexpected. For example, the user clicks on a delete button by mistake instead of Save button. If the application confirms only deletion, a message box comes, which alerts the user instantly. She understands some thing wrong happened. This helps her. But what if the save button also has a confirmation box? She expects it so she clicks yes or no without reading the contents, and yes, the damage is done!
  6. Another way to avoid confirmation boxes is allow users to undo the action. Instead of confirming the deletion, the application can allow the user to delete it, and if she did it by mistake, she can undelete it.

4. Watch out mistake users make.

In hotel industry they believe customer is always right. In the same way belive that users are always right. if they make a mistake, that is your problem. I have heard developers saying if the users don't use the application correctly, the developers cannot help. But think, why can't they use it correctly? That means you need to improve usability of your application.

Understand people use computers to avoid mistakes. So, if they again make mistakes, there is a problem.

At first you may think that an ATM Application has nothing to do with people forgetting to collect their card from ATM. But think again. Why do they forget? Their primary target when they come to ATM is collect money. If they get money first, they will happily go, leaving behind their cards. But, if the application gives back the card first, people will collect it and wait for money. Not the other way.

In the similar way think about your scenario and how to improve your application.

5. Follow the Standards

If you are developing a windows application, web application or a mobile application, understand the standards in that platform and follow it. Users may not know all the standards, but they follow it subconsciously. It helps them to do things right intuitively. It may be small things like putting ... in buttons, which lead to another screens, or using blue color for links. But they make a huge difference.

Well, if you don't break standards, how can you try innovation? Yes, you need to break it occasionally, but make sure you do it for the benefit of users, not for your personal preferences. Alan Cooper says in his famous book About Face "Break the standards only if you have a good reason". But don't make it an excuse to ignore standards. And if you break it, break it consistently.

Conclusion

These just a few tips. Keep in mind your users and their target and you can make your application more user friendly.

Click here to leave a comment.