npm- Specifying dependencies and devDependencies in a package.json file

Install packages required by your application in production:

npm install [package name]

 

Install packages that are only needed for local development and testing:

npm install [package name] --save-dev

NPM cheat sheet:
https://kapeli.com/cheat_sheets/npm.docset/Contents/Resources/Documents/index

Specifying dependencies and devDependencies in a package.json fileTo specify the packages your project depends on, you must list them as “dependencies” or “devDependencies” in your package’s package.json file. When you (or another user) run npm install, npm will download dependencies and devDependencies that are listed in package.json that meet the semantic version requirements listed for each. To see which versions of a package will be installed, use the semver calculator.”dependencies”: Packages required by your application in production.”devDependencies”: Packages that are only needed for local development and testing.

To specify the packages your project depends on, you must list them as "dependencies" or "devDependencies" in your package’s package.json file. When you (or another user) run npm install, npm will download dependencies and devDependencies that are listed in package.json that meet the semantic version requirements listed for each. To see which versions of a package will be installed, use the semver calculator.

  • "dependencies": Packages required by your application in production.
  • "devDependencies": Packages that are only needed for local development and testing.

Source: Specifying dependencies and devDependencies in a package.json file | npm Documentation

Javascript debugging helper – Count number of eventlisteners in Chrome console

Paste and run one of the code blocks below in chrome console to get eventlisteners count.

//eventlisteners counter - grouped summary
Array.from(document.querySelectorAll('*'))  .reduce(function(pre, dom){
    var evtObj = getEventListeners(dom)
    Object.keys(evtObj).forEach(function (evt) {
      if (typeof pre[evt] === 'undefined') {
        pre[evt] = 0
      }
      pre[evt] += evtObj[evt].length
    })
    return pre
  }, {})
  
//_-------------------------------------------
  
  // //eventlisteners - totalcount
  var totalCount = 0;
  Array.from(document.querySelectorAll('*')).reduce(function(pre, dom){
    var evtObj = getEventListeners(dom)
    Object.keys(evtObj).forEach(function (evt) {
      if (typeof pre[evt] === 'undefined') {
        pre[evt] = 0
      }
      // pre[evt] += evtObj[evt].length
	  totalCount += evtObj[evt].length;
    })
    return totalCount;
  }, {})
  
  
  //---------------------------------------

 

jasmine parameterized unit test – Stack Overflow

Based on piotrek’s answer and the article Parameterized testing in Javascript, you could also use the following approach which uses ES6 syntax:

[ 
['abc', 3], 
['ab', 2], 
['', 0],
].forEach(([string, expectedLength]) => { 
it(`should return length ${expectedLength} for string "${string}"`, 
() => { expect(string.length).toBe(expectedLength); });
});

I have tested it with the Jest test framework, but it should work with Jasmine as well.

Source: jasmine parameterized unit test – Stack Overflow

How to use underscore lib from DefinitelyTyped with typescript? – Stack Overflow

Step 1. install type definitions (e.g. vs code intellisense) to project:
npm install –save @types/underscore

(https://www.npmjs.com/package/@types/underscore)

 

Step 2. import to ts file:

import * as _ from “underscore”;

Source: How to use underscore lib from DefinitelyTyped with typescript? – Stack Overflow

TypeScript vs. C#: LINQ

TypeScript counterparts for C# LINQ.

Source: TypeScript vs. C#: LINQ
All of below are copied from https://decembersoft.com in case that blog post disappears in future, I save it here for time keeping. Let me know if its a problem.

TypeScript has no equivalent for the language-integrated-natural-query aspect of LINQ. (hey, isn’t that literally the whole acronym?)

True, you can’t write the following LINQ statement in TypeScript

var adultUserNames =  from u in users  where u.Age >= 18  select u.Name;

However, the IEnumerable<T> extension methods, which are at the heart of LINQ, have equivalents in TypeScript (or can be emulated).

Aggregate

// C#var leftToRight = users.Aggregate(initialValue, (a, u) => /* ... */);
// TypeScriptconst leftToRight = users.reduce((a, u) => /* ... */, initialValue);const rightToLeft = users.reduceRight((a, u) => /* ... */, initialValue);

All

// C#var allReady = users.All(u => u.IsReady);
// TypeScriptconst allReady = users.every(u => u.isReady);

Any

// C#var isDirty = users.Any(u => u.IsDirty);
// TypeScriptconst isDirty = users.some(u => u.isDirty);

Append

// C#var allUsers = users.Append(oneMoreUser);
// TypeScriptconst allUsers = [ ...users, oneMoreUser ];

Average

// C#var avgAge = users.Average(u => u.Age);
// TypeScriptif (users.length < 1) {  throw new Error('source contains no elements');}const avgAge = users.reduce((a, u) => a + u.age, 0) / users.length;

Cast

// C#var people = users.Cast<Person>();
// TypeScriptconst people = users as Person[];// Note: not semantically the same. The C# version throws an exception// if any of the users can't be cast to type Person.

Concat

// C#var allUsers = users.Concat(moreUsers);
// TypeScriptconst allUsers = [ ...users, ...moreUsers ];

Contains

// C#var hasAdmin = users.Contains(admin);
// TypeScriptconst hasAdmin = users.includes(admin); // Use a polyfill for IE support

Count

// C#var n = users.Count();
// TypeScriptconst n = users.length;

DefaultIfEmpty

// C#var nonEmptyUsers = Enumerable.DefaultIfEmpty(users);
// TypeScriptconst nonEmptyUsers = users.length ? users : [ null ];

Distinct

// C#var uniqueNames = users.Select(u => u.Name).Distinct();
// TypeScriptconst uniqueNames = Object.keys(  users.map(u => u.name).reduce(    (un, u) => ({ ...un, n }),    {}  ));

ElementAt

// C#var nth = users.ElementAt(n);
// TypeScriptif (n < 0 || n > users.length) {  throw new Error('Index was out of range');}const nth = users[n];

ElementAtOrDefault

// C#var nth = users.ElementAtOrDefault(n);
// TypeScriptconst nth = users[n];

Empty

// C#var noUsers = IEnumerable.Empty<User>();
// TypeScriptconst noUsers: User[] = [];const noUsers = [] as User[];

Except

// C#var maleUsers = users.Except(femaleUsers);
// TypeScriptconst maleUsers = users.filter(u =>  !femaleUsers.includes(u) // Use a polyfill for IE support);

First

// C#var first = users.First();
// TypeScriptif (users.length < 1) {  throw new Error('Sequence contains no elements');}const first = users[0];

FirstOrDefault

// C#var first = users.FirstOrDefault();
// TypeScriptconst first = users[0];

List.ForEach

// C#users.ToList().ForEach(u => /* ... */);
// TypeScriptusers.forEach(u => /* ... */);

GroupBy

// C#var usersByCountry = users.GroupBy(u => u.Country);
// TypeScriptconst usersByCountry = users.reduce((ubc, u) => ({  ...ubc,  [u.country]: [ ...(ubc[u.country] || []), u ],}), {});

Intersect

// C#var targetUsers = usersWhoClicked.Intersect(usersBetween25And45);
// TypeScriptconst targetUsers = usersWhoClicked.filter(u =>  usersBetween25And45.includes(u) // Use a polyfill for IE support);

Last

// C#var last = users.Last();
// TypeScriptif (users.length < 1) {  throw new Error('Sequence contains no elements');}const last = users[users.length - 1];

LastOrDefault

// C#var last = users.LastOrDefault();
// TypeScriptconst last = users[users.length - 1];

Max

// C#var oldestAge = users.Max(u => u.Age);
// TypeScriptif (users.length < 1) {  throw new Error('source contains no elements');}const oldestAge = users.reduce((oa, u) => Math.max(oa, u.age), 0);

Min

// C#var youngestAge = users.Min(u => u.Age);
// TypeScriptif (users.length < 1) {  throw new Error('source contains no elements');}const youngestAge = users.reduce((ya, u) => Math.min(ya, u.age), Number.MAX_VALUE);

OfType

// C#var bots = users.OfType<Bot>();
// TypeScript// No equivalent

OrderBy / ThenBy

// C#var sorted = users.OrderBy(u => u.Age).ThenBy(u => u.Name);
// TypeScriptconst sorted = users.sort((a, b) => {  const ageDiff = b.age - a.age;  if (ageDiff) return ageDiff;  return a.name.localeCompare(b.name); // Use a polyfill for IE support});

Reverse

// C#var backwards = users.Reverse();
// TypeScriptconst backwards = users.reverse();// Caution: users is also reversed!

Select

// C#var names = users.Select(u => u.Name);
// TypeScriptconst names = users.map(u => u.name);

SelectMany

// C#var phoneNumbers = users.SelectMany(u => u.PhoneNumbers);
// TypeScriptconst phoneNumbers = users.reduce((pn, u) => [ ...pn, ...u.phoneNumbers ], []);

Single

// C#var user = users.Single();
// TypeScriptif (users.length > 1) {  throw new Error('The input sequence contains more than one element');}else if (!users.length) {  throw new Error('The input sequence is empty');}const user = users[0];

SingleOrDefault

// C#var user = users.Single();
// TypeScriptconst user = users[0];

Skip

// C#var otherUsers = users.Skip(n);
// TypeScriptconst otherUsers = users.filter((u, i) => i >= n);

SkipWhile

// C#var otherUsers = users.SkipWhile(predicate);
// TypeScriptlet i = 0;while (i < users.length && predicate(users[i++]));const otherUsers = users.slice(i - 1);

Sum

// C#var totalYears = users.Sum(u => u.Age);
// TypeScriptif (users.length < 1) {  throw new Error('source contains no elements');}const totalYears = users.reduce((ty, u) => ty + u, 0);

Take

// C#var otherUsers = users.Take(n);
// TypeScriptconst otherUsers = users.filter((u, i) => i < n);

TakeWhile

// C#var otherUsers = users.TakeWhile(predicate);
// TypeScriptlet i = 0;while (i < users.length && predicate(users[i++]));const otherUsers = users.slice(0, i - 1);

Union

// C#var allUsers = someUser.Union(otherUsers);
// TypeScriptconst allUsers = otherUsers.reduce((au, u) =>   au.includes(u) // Use a polyfill for IE support    ? au    : [ ...au, u ]}), someUsers));

Where

// C#var adults = users.Where(u => u.Age >= 18);
// TypeScriptconst adults = users.filter(u => u.age >= 18);

Zip

// C#var matches = buyers.Zip(sellers, (b, s) => new { Buyer = b, Seller = s });
// TypeScriptconst matches = [];for (let i = 0; i < buyers.length && i < sellers.length; i++) {  matches.push({    buyer: buyers[i],    seller: sellers[i],  });}

How to include and use jQuery in Angular CLI project

Tested in angular version 7:

  1. install jquery:
    npm install jquery
    install jquery typescript intellisense:
    npm install @types/jquery
  2. edit the angular.json file in root folder:
    in the architect / build / scripts location, add this:

    "scripts": [ "./node_modules/jquery/dist/jquery.min.js" ]
  3. To use jquery inside a component.ts add this import at the top:
    import $ from ‘jquery’;

    Example code to check for functionality:
    component html:

    <button (click)="testJQuery()">Test jquery</button>
    component.ts:
    testJQuery() {
    $('html').fadeOut();
    $('html').fadeIn();
    }
    Click on the button should fade out and fade in the entire page.

Source: How to include and use jQuery in Angular CLI project

json2typescript – npm

NPM Package for converting from JSON to TypeScript object.

json2typescript In Angular 2 applications, everyone consumes JSON API’s from an external source. Type checking and object mapping is only possible in TypeScript, but not in the JavaScript runtime. As the API may change at any point, it is important for larger projects to verify the consumed data. json2typescript is a small package containing a helper class that maps JSON objects to an instance of a TypeScript class. After compiling to JavaScript, the result will still be an instance of this class. One big advantage of this approach is, that you can also use methods of this class.

Source: json2typescript – npm