JavaScript frequently used functions

This is a handy reference for frequently used JavaScript functions;

Shorten the console log

Instead of writing console.log() again and again in code, we can bind it;

//tired of typeing console.log. shorten it
    const log = console.log.bind(document);
    log("does it works?");
    log("yes");

Merge two arrays into one

If you want to merge two arrays of any size into a single array you can use the concate JavaScript function.

//merge two arrays
    const array1 = ["one", "two", "three"]
    const array2 = ["four", "five", "six"]

    const merged = array1.concat(array2)
    console.log(merged)
    //Output:
    //(6) ['one', 'two', 'three', 'four', 'five', 'six']

Merge two objects into one

If you working with objects you can merge them together with this simple trick.

//merge two objects into one
    const user = {
        name: "Shahzad",
        gender: "Male"
    };
    const artcile = {
        title: "Born on the Fourth of July",
        publishDate: "12/14/2021"
    };
    const summary = {...user, ...artcile}
    console.log(summary)
    //Output:
    /*
    gender: "Male"
    name: "Shahzad"
    publishDate: "12/14/2021"
    title: "Born on the Fourth of July"
    */

Shorten an array

There exist an easy way for web developers to shorten an array. You need to use the length method and pass a number that is smaller than the actual array size.

//shorten an array
    const big_array = ["one", "two", "three", "four", "five", "six"]
    big_array.length = 3
    console.log(big_array)
    //Output:
    //(3) ['one', 'two', 'three']

Shuffle an array

Sometimes you want to randomize the values within an array. To achieve this you can use the Array.sort function with a random compareFunction.

//shuffle an array
    const array = ["one", "two", "three", "four", "five", "six"]
    array.sort( function(){ return Math.random() - 0.5})
    console.log('shuffling array')
    console.log(array)

Use isNum to verify a number

With this function, you can check whether a value or variable is a number (int, float, etc) or not.

//use isNum to verify Number
    function isNum(n) {return !isNaN(parseFloat(n)) && isFinite(n);}

    console.log(isNum(4125))        //true
    console.log(isNum(50))          //true
    console.log(isNum("jQuery"))    //false

Use isStr to verify a string

With this function, you can check whether a value or variable is in string format or not.

//use isStr to verify string
    const isStr = value => typeof value === 'string';

    console.log(isStr("jQuery"))    //true
    console.log(isStr(4125))        //false
    console.log(isStr(true))        //false

Use isNull

Often it is useful to check if a result or data is null.

//use isNull
    const isNull = value => value == null || value === undefined;

    console.log(isNull(null))   //true
    console.log(isNull())       //true
    console.log(isNull(123))    //false
    console.log(isNull("s"))    //false

Calculate the performance of a function

If you want to check how long a function runs you can use this approach in your program.

//Calculate the performance of a function
    const start = performance.now();
    //business program
    const end = performance.now();
    const total = start - end
    console.log("function takes " + total + " milisecond");

Remove duplicates from an array

We often encounter an array with duplicated data in it and use a loop to remove those duplicates. This function can remove duplicates in an easy way without using a loop.

//Remove duplicates from an array
    const duplicate_array = array => [...new Set(array)]
    console.log(duplicate_array([
        "One", "Two", "Three", "Two", "Four",
        "One", "Two", "Three", "Two", "Five",
        "Three", "One", "Four", "Two", "Five"]))

    //Output:
    //(5) ['One', 'Two', 'Three', 'Four', 'Five']

Use logical AND/OR for conditions

Instead of using an if-condition, you can use a logical AND/OR. This can be used within a function for executing commands.

//Use logical AND/OR for conditions
    const input = 2
    input == 4 && console.log("it is 4")
    input == 4 || console.log("it is not 4")

    //can also be used for assigning values
    function defaultTo4(arg) {
        arg = arg || 4; //arg will have 4 as a default value if not set
        console.log(arg)
    }
    let arg1 = 2
    let arg2 = null
    defaultTo4(arg1)    //2
    defaultTo4(arg2)    //4

Ternary operator

The ternary operator is just cool. You can avoid bad-looking nested conditional if..elseif..elseif with ternary operators.

//Ternary operator
    function temperature(temp){
        return (temp > 39 || temp < 35.5) ? 'Stay home'
        : (temp < 37.5 && temp > 36.5) ? 'Go out and play'
        : (temp <= 39 && temp >= 35.5) ? 'Take some rest'
        : ''
    }

    console.log(temperature(38))    //take some rest
    console.log(temperature(36))    //take some rest
    console.log(temperature(39.1))  //Stay home
    console.log(temperature(35.1))  //Stay home
    console.log(temperature(37))    //Go out and plan

Resources

https://docs.microsoft.com/en-us/javascript/

Using vanilla ADO.NET

This is how;

var zoo = new List<Zoo>();
int paramValue = 5;
var queryString = @"SELECT animalName FROM Jungle";

// Create and open the connection in a using block. This ensures that all resources will be closed and disposed when the code exits.
using (SqlConnection connection = new SqlConnection(connectionString))
{
   // Create the Command and Parameter objects.
   SqlCommand command = new SqlCommand(queryString, connection);
   //command.Parameters.AddWithValue("@howManyLegs", paramValue);

  // Open the connection in a try/catch block. Create and execute the DataReader, writing the result set to the console window.
  try
  {
      connection.Open();
      SqlDataReader reader = command.ExecuteReader();
      while (reader.Read())
      {
           Console.WriteLine("\t{0}", reader[0]);
           var animal = new Animal
           {
                AnimalName = reader[0].ToString()
           };
           zoo.Add(animal);
       }
       reader.Close();
  }
  catch (Exception ex)
  {
       Console.WriteLine(ex.Message);
  }
  Console.ReadLine();
}

Resources

https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ado-net-code-examples

What does “where T : class, new()” mean?

Let’s start with a piece of code;

void Add<T>(T item) where T : class, new();

It’s called a ‘constraint’ on the generic parameter T. It means that T must be a reference type (a class) and that it must have a public default constructor.

That means T can’t be an int, float, double, DateTime or any other struct (value type). It could be a string, or any other custom reference type, as long as it has a default or parameter-less constructor.

For understanding we can break it into two parts;

where T : class

Means that the type T must be a reference type (not a value type).

where T : new()

Means that the type T must have a parameter-less constructor. Having this constraint will allow you to do something like T field = new T(); in your code which you wouldn’t be able to do otherwise.

We then combine the two using a comma to get:

where T : class, new()

Just to clarify, if you don’t have the class clause as part of the where T…, then it is safe to use int, float, double etc

Here is an example;

struct MyStruct { } // structs are value types

class MyClass1 { } // no constructors defined, so the class implicitly has a parameter less one

class MyClass2 // parameter less constructor explicitly defined
{
    public MyClass2() { }
}

class MyClass3 // only non-parameter less constructor defined
{
    public MyClass3(object parameter) { }
}

class MyClass4 // both parameter less & non-parameter less constructors defined
{
    public MyClass4() { }
    public MyClass4(object parameter) { }
}

interface INewable<T>
    where T : new()
{
}

interface INewableReference<T>
    where T : class, new()
{
}

class Checks
{
    INewable<int> cn1; // ALLOWED: has parameter less ctor
    INewable<string> n2; // NOT ALLOWED: no parameter less ctor
    INewable<MyStruct> n3; // ALLOWED: has parameter less ctor
    INewable<MyClass1> n4; // ALLOWED: has parameter less ctor
    INewable<MyClass2> n5; // ALLOWED: has parameter less ctor
    INewable<MyClass3> n6; // NOT ALLOWED: no parameter less ctor
    INewable<MyClass4> n7; // ALLOWED: has parameter less ctor

    INewableReference<int> nr1; // NOT ALLOWED: not a reference type
    INewableReference<string> nr2; // NOT ALLOWED: no parameter less ctor
    INewableReference<MyStruct> nr3; // NOT ALLOWED: not a reference type
    INewableReference<MyClass1> nr4; // ALLOWED: has parameter less ctor
    INewableReference<MyClass2> nr5; // ALLOWED: has parameter less ctor
    INewableReference<MyClass3> nr6; // NOT ALLOWED: no parameter less ctor
    INewableReference<MyClass4> nr7; // ALLOWED: has parameter less ctor
}

Resources

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters

https://stackoverflow.com/questions/4737970/what-does-where-t-class-new-mean

nuget package restore

If you are using private feed then make sure you have installed this;

https://github.com/Microsoft/artifacts-credprovider

I ran this command in powershell (admin mode);

iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/microsoft/artifacts-credprovider/master/helpers/installcredprovider.ps1'))

I have to run this command to restore packages;

dotnet restore –interactive

This command will open up a window and ask you to login to Microsoft website with a code. Login to https://microsoft.com/devicelogin and enter the code. This will do some sort of IDE verification. Close VS and reopen. You should be able to see all of your custom and nuget packages restored.

I found this alternative today;

dotnet restore projectName

This will restore the packages.

From within Visual Studio you can use the Package Manager Console to also update the packages. This has the benefit that any PowerShell scripts will be run as part of the update where as using NuGet.exe will not run them. The following command will update all packages in every project to the latest version available from nuget.org.

Update-Package

You can also restrict this down to one project.

Update-Package -Project YourProjectName

If you want to reinstall the packages to the same versions as were previously installed then you can use the -reinstall argument with Update-Package command.

Update-Package -reinstall

You can also restrict this down to one project.

Update-Package -reinstall -Project YourProjectName

The -reinstall option will first uninstall and then install the package back again into a project.

Close and restart VS. Hopefully this will restore the packages.

Another problem might be yellow triangle icon next to package references. To solve this, make sure you are targeting same framework in multiple projects. Here is a discussion about this;

https://stackoverflow.com/questions/20186216/why-do-i-get-a-warning-icon-when-i-add-a-reference-to-an-mef-plugin-project

Resources

https://github.com/dotnet/sdk/issues/10189

https://stackoverflow.com/questions/6876732/how-do-i-get-nuget-to-install-update-all-the-packages-in-the-packages-config

Project targeting multiple framework in .NET

Edit the .csproj file to support the target frameworks; for example change.

<TargetFramework>netcoreapp2.1</TargetFramework>
to:
<TargetFrameworks>netcoreapp2.1;net45</TargetFrameworks>

Make sure that you change the XML element changed from singular to plural (add the “s” to both the open and close tags).

Resources

https://docs.microsoft.com/en-us/nuget/create-packages/multiple-target-frameworks-project-file

Multi-Targeting Frameworks