JavaScript helper: TryParseInt [TypeScript]

Here’s a quick JavaScript helper snippet to test a string and return a parsed integer value, or a default value if the the parse fails.

Written in TypeScript.

 

/**
 * Try to parase an integer value from a string. Returns the number if successful, otherwise return a default value.
 * @param value The string with an integer to parase.
 * @param defaultValue Default value to return if parsing fails.
 */
public static TryParseInt(value: string, defaultValue: number = 0): number {
	let parsedValue = parseInt(value, 10);

	if (isNaN(parsedValue)) {
		// Failed to parse. Return the default value.
		return defaultValue;
	} else {
		// Return the parsed value.
		return parsedValue;
	}
}

TypeScript: Convert a String Variable to a Number Variable

Sometimes the basics can stump you. And I was stumped this morning when I needed to convert a TypeScript variable of type “string” to a variable of type “number”, including a non-numeric check.

IsNaN() and parseInt() in JavasScript didn’t work because in TypeScript the input parameters are numbers, so immediately that’s a compile time exception.

After a quick search and trusty StackOverflow answer, I came up with the following function:

/**
 * Return the numeric value of a variable if the value is a number, otherwise return zero (0).
 */
function convertToNumber(value: any) : number 
{
  let convertedToNumber: number = 0;

  if (isNaN(Number(value)) === false) {
    convertedToNumber = Number(value);
  }

  return convertedToNumber;
}

 

Running Example

NOTE: You can pop the editor open in a new window by selecting “Edit On StackBlitz” in the bottom-left of the inserted window.
Select the folded-page icon at the top of the left column (below the StackBlizt blue/white icon) to see the list of files.

If you’re using Internet Explorer or there’s just a black window below, here’s the link to the code (and I suggest using a “modern” browser – Chrome and Edge both work): https://stackblitz.com/edit/typescript-x2hpkw.

Tackling Regex – Value cannot start or end with space, but can contain spaces and selected characters, up to max length

Regex Sucks!

But I needed to update a form field regex validation, so I tackled it head-on and won.

As a side note, regular expression creation is also one of the best examples of where Test Driven Development (TDD) works well. You really cannot create or maintain a regex without having all the test cases written first.

 

Validation Requirements

For a value entered in the field, it:

  • Cannot start with a space.
  • Cannot end with a space.
  • May contain a one or more sapces (surrounded by other allowed characters).
  • May also contain the following characters: A-Z, a-Z, 0-0, “-“, “_”, “\”, “/”.
  • If a value is entered in the field the total character count may be from 1 to 20 characters.

 

Regex String

^([A-Za-z0-9\\\/_\-]|([A-Za-z0-9\\\/_\-][A-Za-z0-9\\\/_\- ]{0,18}[A-Za-z0-9\\\/_\-]))$

Regex Summary:

  1. For the first group (green):
    1. If the string contains only 1 character, ensure it is a valid character.
  2. OR, for the second set of 3 groups (purple):
    1. Ensure the first character is a valid character.
    2. Ensure 0-18 of the next characters is a valid character.
    3. Ensure the last character is a valid character.
    4. The combination of point 2.1, 2.2 & 2.3 handle scenarios of 2 up to 20 characters.

 

Test Data

kkdkd df sdf lk aj33<-- Pass
12345678901234567890<-- Pass
kjlf l-Ka034-/\_ kj0<-- Pass
adsfdsafsdaf dsfsdfa<-- Pass
dlASjd83_-/\dfdsfsda<-- Pass
adsfsdas  sdafsdafsa<-- Pass: Contains multiple spaces in a row
dsfsdf<-- Pass
2<-- Pass
11<-- Pass
111<-- Pass
- dsf<-- Pass
-df<-- Pass
/dsaf<-- Pass
\asdf<-- Pass
_asdf<-- Pass
_ sdfjlksdaflk jasdf<-- Pass

123456789012345678901<-- Fail. More than 20 characters
 asdf<-- Fail: Starts with a space
adsfsdas  sdafsdafs#<-- Fail: Ends with a #
 adsfsdafsdfsdfsadds<-- Fail: Starts with a space
dfsdafljkasdfklsdsd <-- Fail: Ends with a space
#<-- Fail: Invalid character only
 <-- Fail: Space only
2 <-- Fail: Ends with space
 2<-- Fail: Starts with a space

<-- Ignore: Blank line

 

See it in action

https://regex101.com/r/2uMivO/6

 

Tricky Bits

It took some trial and error to get this and using https://regex101.com was a huge help and time saver.

My final problem was allowing a single character, and that was whee the OR (“|”) came in, adding it to the start of the group.

Working with JavaScript dates deserialized from JSON

This is a quick post inspired by a problem I helped a colleague with yesterday.

The problem is a “date.getFullYear is not a function” error was thrown when calling getFullYear() on a TypeScript Date object.

This was happening when the Date object was populated from a deserialized JSON string and the deserialization was silently failing in the background in the app.

It happens due to the format of the date string, and on top of that, the string is in the format “dd/mm/yyyy” (the short date format used by most of the world)..
JavaScript being what it is, it doesn’t like this for dates like “18/05/2018” (18th May) because it actually wants to do a conversion on “05/18/2018” (US short date format).
More importantly, you can’t implicitly deserialize a string representation of a date to a JavaScript Date object. How does the dezerializer (in this case JSON.parase()) know the string is really a date?

How do we fix this?

There are 2 parts to the answer:

  1. We need to explicitly set the target/deserialized date variable/field to a Date()
    i.e. myObject.myDate = new Date(“date-string-in-accepted format”);
    For example: myObject.myDate = new Date(“05/18/2018”).
  2. Ensure the string we are passing into the Date() object is in an allowed format (best format is ISO: yyyy-mm-dd).
    For example:
    myObject.myDate = new Date(“2018-05-18”) – using ISO date format.
    myObject.myDate = new Date(“05/18/2018”) – using US date format.

Below you can see it a quick running code sample I whipped up to demonstrate this.

Play around with commenting.uncommenting the “json = “…”;” lines and the “let dataObject: DataObject = JSON.parse(json);” line.

Running Example

NOTE: You can pop the editor open in a new window by selecting “Edit On StackBlitz” in the bottom-left of the inserted window.
Select the folded-page icon at the top of the left column (below the StackBlizt blue/white icon) to see the list of files.

If you’re using Internet Explorer or there’s just a black window below, here’s the link to the code (and I suggest using a “modern” browser – Chrome and Edge both work): https://stackblitz.com/edit/typescript-riapny.

&$ prefix for PHP function argument

The &$ prefix of an argument name passed into a PHP function means the argument is passed “by reference” (as opposed to “by value).

For example:

function publish_contributor_post($arg1, &$arg2)
{
   ... 
}

In this example arg2 is passed “by reference”.

See also: https://stackoverflow.com/questions/20419613/php-string-what-does-this-mean

Concatenation in PHP produces ‘0’ (zero)

If you’re concatenating a string in PHP and the result is a zero (“0”), check you haven’t mixed up your languages and used a “+” instead of “.” as your concatenation operator.

As a regular developer in C# and JavaScript regular, I sometimes write “$result = $part1 + $part2″ whereas I should write “$result = $part1 . $part2″.

A simple example of an Observable/Subscribe function in TypeScript

I had to work with Observables in JavaScript (RxJS) today and found it, well, bloody hard to find some good examples.

Actually, it’s hard to know what to even search for to find information about Observables (do I search in relation to Angular, Javascript, ECMAScript, TypeScript…?). I found it even harder to decipher most of the highly technical documentation that has been written.

Most examples I found were around making HTTP calls to a server and went no further.

The problem I was solving was to wait for a function that received the results of an HTTP call to finish before then executing other code. That is:

main() — calls –> load() — calls –> httpRequester()

What I need is for load() to return an Observable to main() so I can schedule other code to run only once httpRequester(), and hence load(), where both finished.

After half an hour of looking at examples I figured it out, and for everyone’s benefit, I have created a simple and hopefully easy to understand example on StackBilitz.

Running Example

NOTE: You can pop the editor open in a new window by selecting “Edit On StackBlitz” in the bottom-left of the inserted window.

If you’re using Internet Explorer or there’s just a black window below, here’s the link to the code (and I suggest using a “modern” browser – Chrome and Edge both work): https://stackblitz.com/edit/typescript-vtrstc.

Sorting algorithms can be difficult, but I gave it a crack and here’s what I produced

I find sorting algorithms difficult. I also find recursion algorithms difficult (that’s another story). My brain isn’t really wired very well for algorithmic thinking, which is probably an odd thing for a software developer to say.

My day job today required me to write a reasonably complex sorting algorithm in JavaScript on a data set that required grouping and multiple layers of sub-sorting. Conceptually it’s actually relatively easy – as this answer on StackOverflow suggests – but life is never that simple.

In order to focus on just the algorithm during development, I coded it in StackBlitz, a relatively new online IDE/sandpit for JavaScript based projects.
Below is my running example, developed with TypeScript. All up it took me about 6 hours (including understanding the requirements, a couple of missteps, and cleaning up the code, then refactoring into modules/files).

If the data names seem strange that’s because it’s for biological data. I’ve left out all the unnecessary fields and focused purely on the fields that need sorting (except for the ID and Rnd fields).

I’ve added the sorting requirements into the code, but here’s what we needed (exactly as received):

  • Group by DSA Category (Specific first, Potential next)
  • Then Group by Locus, get the highest MFI for each locus, and sort locus by highest MFI to lowest
  • Then sort antibody (the same antibody should be grouped together) by MFI highest to lowest.
    [JS: Another way of looking at it: Group by locus, and find the highest MFI for each locus. Then within each locus group by antibody. Then sort antibody within each locus by MFI, highest to lowest. Then step back up to locus and based on the highest MFI found within the locus, sort each locus “group” by that MFI, from highest to lowest.]
  • Then sample date

 

Running Example

NOTE: You can pop the editor open in a new window by selecting “Edit On StackBlitz” in the bottom-left of the inserted window.
Select the folded-page icon at the top of the left column (below the StackBlizt blue/white icon) to see the list of files.
The code is split over multiple .ts (TypeScript) files, and index.ts is the starting point.

If you’re using Internet Explorer or there’s just a black window below, here’s the link to the code (and I suggest using a “modern” browser – Chrome and Edge both work): https://stackblitz.com/edit/js-complex-sort.