Tuesday, 24 December 2019

Generic method for builing a query string of classes in Typescript

This method below can be used in Typescript to build up a query string from a given object of a class instance in Typescript. Use it when performing HTTP(S) GET calls.

  BuildQueryString<T>(input: T): string {
    let q = "?";

    Object.keys(input).forEach(key => q += key + "=" + input[key] + "&");

    if (q.length > 0) {
      q = q.substr(0,q.length-1);
    }

    return q;

    
  }



Sample usage in Angular 8 solution of mine for example:


  async saveSurvey(): Promise<SurveyItem> {
    //debugger
    let s: SurveyItem = {
      Id: 0, LastUpdate: new Date(),
      EquipmentNumber: this.equpimentIdentifier, RoomNumber: this.roomIdentifier,
      PrimaryUsage: this.primaryUsage,
      IsInspected: this.GetBoolean(this.isInspected), IsNotFound: this.GetBoolean(this.isNotFound)
    };
    let q = this.fetcher.GetAPIUrl('savesurvey');
    q += this.fetcher.BuildQueryString(s);
    const response = await this.http.get<SurveyItem>(q, { headers: this.corsHeaders }).toPromise();
    //this.openSnackBar('Lagret utstyr ' + this.equpimentIdentifier);
    this.openSnackBar('Lagret utstyr ' + this.equpimentIdentifier + ' Laster inn liste for utstyr i samme rom også..');

    //After saving survye - update also the properties with updated Id and LastUpdate

    this.SetCurrentSurveyItemPropretiesFromSurveyItem(response);

    this.onRoomSelected(this.roomIdentifier);



    return response;
  }

Monday, 2 December 2019

Eslint Standalone tool

I have created a standalone Eslint tool the last weeks! This tool is available through Npmjs here: https://www.npmjs.com/package/eslint-standalone The source code is available here: https://github.com/toreaurstadboss/eslint-standalone To clone the repo, you can run this command:

git clone https://github.com/toreaurstadboss/eslint-standalone.git

This animated gif shows how the tools shows linting capabilities. The loaded .eslintrc.js file errors if there are ES6 syntax, which does not work well in Internet Explorer. This is done by specifying env->es6 set to true and parserOptions->ecmaVersion set to '5'. Why would you even consider supporting Internet Explorer as a browser for your products ? Well, in the real world, some customers still use Internet Explorer due to company restrictions and compability reasons. So this standalone tool together with .eslintrc.js file below should help you check files conforming to ES5 Syntax and thereby supporting Internet Explorer.

module.exports = {
  "plugins": ["ie11"],
  "env": {
    "browser": true,
    "node": true,
    "es6": false
  },
  "parserOptions": {
    "ecmaVersion": 5,
  },
  "rules": {
    "ie11/no-collection-args": ["error"],
    "ie11/no-for-in-const": ["error"],
    //"ie11/no-loop-func": ["warn"],
    "ie11/no-weak-collections": ["error"]
  }
};

To check that your Javascript code works using this tool, add the .eslinrc.js file above in the folder of your project (or any parent folder on that media disk volume). Then run the command eslint-standalone.exe after adding the .eslintrc.js file. You should then have outputted to the command line the errors (or warnings found) of ES6 Syntax, which IE does not support. Note that I have not added functionality for '--fix' with this ESLint tool yet. You must inspect the warnings and errors reported and manually adjust/fix the Javascript source code. Also note that this tool only supports looking at .js and .htm and .html files. I tried adding .cshtml files in the list of file globs supported, but the tool could not understand Razor syntax. Feel free to give me some tips here if you know how to add this as a support. Also note that it is additional documentation to be found for this tool on the Npmjs.org site and also in the GitHub repository.
eslint-standalone.exe 
The sample screen shot shows how to run the tool from the command line (simple command). I deliberately added an arrow method in a Javascript file and the tool quickly spots this issue. For a medium sized project the tool takes only 5-10 seconds to execute.

Friday, 15 November 2019

Sorting array word-wise in Javascript

Sometimes it is nice to sort arrays word-wise in Javascript. This means sorting not the entire column value,

/**
 * Summary: Sorts alphabetaically word-wise to be used in e.g. a Select2Js control. Specify the n-word to start sorting with. 
 *
 * Alphabetically sorts by each word
 * @param {Number}   startWordIndex The 'n-word' to begin sorting with  *
 * @param {boolean}  isAscending The direction of sorting - true means ascending, false means descending
 * @return {type} Return sort comparison value. If 0, the sorting is tie, if < 0 the element a preceeds b
 */
(function () {
    var sortFunction = function sortFunctionTemplate(isAscending, startWordIndex, valueSelector, a, b) {
        var aValue = valueSelector(a);
        var bValue = valueSelector(b);
        var astripped = aValue.split(' ');
        var bstripped = bValue.split(' ');
        var wordLength = Math.min(astripped.length, bstripped.length);

        var compareValue = 0;
        for (var i = startWordIndex; i < wordLength; i++) {
            compareValue = astripped[i].localeCompare(bstripped[i]);
            if (compareValue !== 0) {
                break;
            }
        }
        if (compareValue === 0) {
            if (astripped.length > bstripped.length) {
                compareValue = 1;
            } else if (astripped.length < bstripped.length) {
                compareValue = 1;
            }
        }
        return compareValue * (isAscending ? 1 : -1);
    };
    if (typeof (Array.prototype.sortWordwise) === 'undefined') {
        // ReSharper disable once NativeTypePrototypeExtending
        Array.prototype.sortWordwise = function sortWordwise(startWordIndex, isAscending, valueSelector) {
            if (valueSelector === null) {
                valueSelector = function (item) {
                    return item;
                };
            }
            //console.log('sorterer word-wise... ');

            return this.sort(sortFunction.bind(this, isAscending, startWordIndex, valueSelector));

        };

    }
})();

Example how to use this method: Here we use the Select2.js jQuery plugin to do our custom sorting to sort word-wise. I only consider the text after the ':' in my specific use case and I supply the starting index - sorting by the nth-word 1 (i.e. second word and so on) and supply a value selector function also. Select2.Js also retrieves a matcher function to specify the matching to be done case-insensitive (the find item in list function of the select 2 js control in this specific case).

$('.stentGraftfabrikatpicker').select2({
      width: "element",
            sortResults: function(data) {
                var velgVerdi = data[0];
                var ret = [velgVerdi];
                var dataToBeSorted = data.splice(1);
                return ret.concat(
                    dataToBeSorted.sortWordwise(1, true, function(item) {
                        var value = item.text;
                        return value.indexOf(':') >= 0 ? value.substring(value.indexOf(':') + 1) : value;
                    })
                );
            },
      matcher: function(term, text) {
       return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
      },
      allowClear: true
    });