Tari Ibaba

Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

How to Fix the Cannot Find Name ‘it’ Jest Error in TypeScript

To fix the “cannot find name ‘it'” Jest error, install the type definitions for Jest with npm i -D @types/jest and add them to the types array in your tsconfig.json file.

This error occurs when you try to use the it() function from Jest in a TypeScript file, but TypeScript cannot find the type definitions for the package.

Here is an example of the error occurring in Visual Studio Code:

The "cannot find name it" Jest error occurring in Visual Studio Code.

index.ts

// Cannot find name 'it'. Do you need to install type
// definitions for a test runner? Try 
// `npm i --save-dev @types/jest` or 
// `npm i --save-dev @types/mocha`. ts(2582)

describe('example', () => {
  it('adds two numbers together', () => {
    expect(2 + 2).toBe(4);
  });
});

Install the type definitions for Jest by running the following command in a terminal at the root directory of your project:

npm i -D @types/jest

If you didn’t already have Jest installed, you can install it with the type definitions in one command:

npm i -D @types/jest jest

Add typings to tsconfig.json types array

In some cases, this is all you need to do and the error will stop. But if it persists, you’ll need to add jest to the types array in your tsconfig.json file, so it looks something like this:

tsconfig.json

{
  "compilerOptions": {
    "types": [
      // ... other types
      "jest"
    ]
    // ..other settings
  }
}

Include test files

If the error still doesn’t go away, ensure that TypeScript does not ignore the directory containing your test files. If you’ve set the include array in your tsconfig.json file, ensure the patterns specified in this array match the directory where your test files are located.

For example, if your tests are located in a src directory, TypeScript will detect them with a configuration like this:

tsconfig.json

{
  "compilerOptions": {},
  "include": ["src/**/*"],
}

But if they’re located in a tests directory, we’ll need to add an additional glob pattern to make TypeScript detect them:

tsconfig.json

{
  "compilerOptions": {},
  "include": [
    "src/**/*",
    "tests/**/*"
  ],
}

We can also include glob patterns to match test files with a specific ending or extension. For example, we can include all files ending with “.spec.ts” and “.test.ts” with the following configuration:

tsconfig.json

{
  "compilerOptions": {},
  "include": [
    "src/**/*",
    "**/*.spec.ts",
    "**/*.test.ts"
  ],
}

How to Convert a String of Numbers to an Array in JavaScript

In this article, we’ll learn how to easily convert a string containing a comma-separated list of numbers to an array of these numbers in JavaScript.

String split() and Array map() Methods

To convert a string of numbers to an array, call the split() method on the string, passing a comma (,) as an argument, to get an array of the string representation of the numbers. Then use the map() method to transform each string in the array into a number. For example:

const str = '1,2,3,4';

const nums = str.split(',').map(Number);
console.log(nums); // [ 1, 2, 3, 4 ]

The String split() method divides a string into an array of characters using the specified separator. We pass a comma to separate the stringified numbers into separate elements in the resulting array.

console.log('1,2,3,4'.split(',')); // [ '1', '2', '3', '4' ]

The Array map() method creates a new array from the result of calling a callback function on each element of the original array. We pass the Number constructor to map(), so Number() will be called on each string in the array to convert it to a number.

We can use the map() method more explicitly like this:

const str = '1,2,3,4';

const nums = str.split(',').map((item) => Number(item));
console.log(nums); // [ 1, 2, 3, 4 ]

You might prefer this approach since it lets you see exactly what arguments you’re passing to the callback function. This can prevent bugs in situations where the callback function behaves differently depending on the number of arguments passed.

Apart from the Number constructor, we can also convert each item in the string array to a number with parseInt():

const str = '1,2,3,4';

const nums = str.split(',').map((item) => parseInt(item, 10));
console.log(nums); // [ 1, 2, 3, 4 ]

parseInt() parses a string and returns an integer of the specified base. We pass 10 as the second argument, so parseInt() uses base 10 to parse the string.

We can also use the unary operator (+) in place of parseInt() or Number(). This operator converts a non-numeric value into a number.

const str = '1,2,3,4';

const nums = str.split(',').map((item) => +item);
console.log(nums); // [ 1, 2, 3, 4 ]

How to Get the Length of a Number in JavaScript

1. length Property of String Representation

To get the length of a number, call the toString() method on the number to convert it to a string, then access the length property of the string, i.e., num.toString().length.

const num1 = 12345;
const num2 = 524;

console.log(num1.toString().length); // 5
console.log(num2.toString().length); // 3

We call the toString() method on the number to get its string representation.

const num1 = 12345;
const num2 = 524;

console.log(num1.toString()); // '12345'
console.log(num2.toString()); // '524'

String objects have a length property that returns the number of characters (UTF-16 code units) in a string. We use this to get the length of the number.

Getting the Length of Floats

For floating point numbers, the decimal point will be included when accessing the length property of the string representation of the float.

const float1 = 123.45; // 5 digits
const float2 = 524.1; // 4 digits

console.log(float1.toString().length); // 6
console.log(float2.toString().length); // 5

To avoid this and get the actual number of digits in the float, simply subtract 1 from length.

const float1 = 123.45; // 5 digits
const float2 = 524.1; // 4 digits

console.log(float1.toString().length - 1); // 5
console.log(float2.toString().length - 1); // 4

2. Math.ceil() and Math.log10() Methods

We can also use a purely mathematical approach to get the length of a number:

function getNumberLength(num) {
  return Math.ceil(Math.log10(num + 1));
}

const num1 = 12345;
const num2 = 524;

console.log(getNumberLength(num1)); // 5
console.log(getNumberLength(num2)); // 3

The Math.log10() method returns the logarithm of a number to the base 10.

console.log(Math.log10(12345)); // 4.091491094267951

And the Math.ceil() method rounds a number up to the next largest integer.

console.log(Math.ceil(4.091491094267951)); // 5

Unfortunately, this method doesn’t work for floats. It only returns the number of digits before the decimal point.

function getNumberLength(num) {
  return Math.ceil(Math.log10(num + 1));
}

const float1 = 123.45; // 5 digits
const float2 = 524.1; // 4 digits

console.log(getNumberLength(float1)); // 3
console.log(getNumberLength(float2)); // 3

How to Get the Substring Between Two Characters in JavaScript

1. String substring(), indexOf() and lastIndexOf() Methods

To get the substring of a string between two of its characters in JavaScript, call the slice() method on the string, passing the index after the first occurrence of the first character as the first argument, and the index of the last occurrence of the second character as the second argument. For example:

function getSubstring(str, char1, char2) {
  return str.substring(
    str.indexOf(char1) + 1,
    str.lastIndexOf(char2)
  );
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, ':', ';');
console.log(substr1); // two

const str2 = 'one?two!three';
const substr2 = getSubstring(str2, '?', '!');
console.log(substr2); // two

The String indexOf() method returns the position of the first occurrence of a value in a string. On the other hand, lastIndexOf() returns the position of the last occurrence of a value in a string.

The String substring() method returns the portion of a string between the start and end indexes, specified by the first and second arguments respectively. We add 1 to the result of indexOf() because we don’t want the first character to be included in the substring that we’re trying to get. However, we don’t need to subtract 1 from the result of lastIndexOf(), because substring() already excludes the character at the specified end index.

If the value doesn’t exist in the string, both indexOf() and lastIndexOf() will return -1. This means that when the first character doesn’t exist in the string, all of the string from the start to the last occurrence of the second character will be included in the string.

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, '-', ';');
console.log(substr1); // one:two

Also, when the second character doesn’t exist, all of the string from the beginning to the first occurence of the first character will be included in the string.

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, ':', '-');
console.log(substr1); // one

Depending on our use case, this might not be what we want. If we want an empty string ('') to be returned when either of the characters doesn’t exist, we’ll need to explicitly check for this:

function getSubstring(str, char1, char2) {
  const char1Index = str.indexOf(char1);
  const char2Index = str.lastIndexOf(char2);
  if (char1Index === -1) return '';
  if (char2Index === -1) return '';
  return str.substring(char1Index, char2Index);
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, '-', ';');
console.log(substr1); // '' (empty string)

const substr2 = getSubstring(str1, ':', '-');
console.log(substr2); // '' (empty string)

2. String split(), Array slice(), and Array join() Methods

Here’s another way to get the substring of a string between two of its characters:

function getSubstring(str, char1, char2) {
  return str
    .split(char1)
    .slice(1)
    .join('')
    .split(char2)
    .slice(0, -1)
    .join('');
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, ':', ';');
console.log(substr1); // two

const str2 = 'one?two!three';
const substr2 = getSubstring(str2, '?', '!');
console.log(substr2); // two

The String split() method divides a string using a specified separator.

const str1 = 'one:two;three';

// [ 'one', 'two;three' ]
console.log(str1.split(':')); 

The Array slice() methods extracts the elements of an array between the start and end indexes, which are specified by the first and second arguments respectively. We pass 1 as the first argument without specifying a second, so slice() extracts from the element at index 1 to the end of the string.

// ['two;three'];
console.log([ 'one', 'two;three' ].slice(1));

We call the Array join() method on the result of slice() to concatenate the elements of the array into a string.

const str1 = 'one:two;three';

// two;three
console.log(['two;three'].join(''));

We split this result again, this time by the second character.

// ['two', 'three'];
console.log('two;three'.split(';'));

We call slice() on the array resulting from this split, passing 0 and -1 as arguments, to copy all the array elements except the last one to a new array.

// [ 'two' ]
console.log(['two', 'three'].slice(0, -1));

Finally, we call join() on this result to get the string between the two characters.

Unlike the first method, this approach handles the case where one of the characters is not in the string by returning an empty string.

function getSubstring(str, char1, char2) {
  return str
    .split(char1)
    .slice(1)
    .join('')
    .split(char2)
    .slice(0, -1)
    .join('');
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, '-', ';');
console.log(substr1); // '' (empty string)

const substr2 = getSubstring(str1, ':', '-');
console.log(substr2); // '' (empty string)

How to Add Minutes to a Date in JavaScript

1. Date setMinutes() and getMinutes() Methods

To add minutes to a Date in JavaScript, call the getMinutes() method on the Date to get the minutes, then call the setMinutes() method on the Date, passing the sum of getMinutes() and the minutes to add.

function addMinutes(date, minutes) {
  date.setMinutes(date.getMinutes() + minutes);

  return date;
}

const date = new Date('2022-05-15T00:00:00.000Z');

const newDate = addMinutes(date, 10);

// 2022-05-15T00:10:00.000Z
console.log(newDate);

Our addMinutes() function takes a Date and the number of minutes to add as arguments, and returns the same Date with the newly added minutes.

The Date getMinutes() method returns a number between 0 and 59 that represents the minutes of the Date.

The Date setMinutes() method takes a number representing minutes and set the minutes of the Date to that number.

If the minutes you specify would change the hour, day, month, or year of the Date, setMinutes() automatically updates the Date information to reflect this.

// 12:00 AM on May 15, 2022
const date = new Date('2022-05-15T00:00:00.000Z');

date.setMinutes(date.getMinutes() + 150);

// 2:30 AM on May 15, 2022
console.log(date); // 2022-05-15T02:30:00.000Z

In this example, passing 150 to setMinutes() increments the Date hours by 2 (120 minutes) and sets the minutes to 30.

Avoiding Side Effects

The setMinutes() method mutates the Date object it is called on. This introduces a side effect into our addMinutes() function. To avoid modifying the passed Date and create a pure function, make a copy of the Date and call setMinutes() on this copy, instead of the original:

function addMinutes(date, minutes) {
  const dateCopy = new Date(date);
  dateCopy.setMinutes(date.getMinutes() + minutes);

  return dateCopy;
}

const date = new Date('2022-05-15T00:00:00.000Z');

const newDate = addMinutes(date, 10);

console.log(newDate); // 2022-05-15T00:10:00.000Z

// Original not modified
console.log(date); // 2022-05-15T00:00:00.000Z

Tip

Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about. This makes it a good practice to limit the number of side-effects in your programs.

2. date-fns addMinutes()

Alternatively, you can use the pure addMinutes() function from the date-fns NPM package to quickly add minutes to a Date.

import { addMinutes } from 'date-fns';

const date = new Date('2022-05-15T00:00:00.000Z');
const newDate = addMinutes(date, 10);

console.log(newDate); // 2022-05-15T00:10:00.000Z

// Original not modified.
console.log(date); // 2022-05-15T00:00:00.000Z

How to Split a Number into an Array in JavaScript

1. Array.from() Method

To split a number into an array in JavaScript, call the Array.from() method, passing the number converted to a string as the first argument, and the Number constructor as the second, i.e., Array.from(String(num), Number). For example:

function splitIntoArray(num) {
  return Array.from(String(num), Number);
}

const arr1 = splitIntoArray(1234);
console.log(arr1); // [ 1, 2, 3, 4 ]

const arr2 = splitIntoArray(4901);
console.log(arr2); // [ 4, 9, 0, 1 ]

The static Array from() method creates a new array from an array-like object, like a String or a Set.

// [ '1', '2', '3', '4' ]
console.log(Array.from('1234'));

The second argument we pass to from() is a map function that is called on every element of the array. We pass the Number constructor function so that each item in the array will be converted to a number.

We can do this more explicitly with the Array map() instance method:

const num = 1234;

// ['1', '2', '3', '4'];
const arrOfStrs = Array.from(String(num));

const arrOfNums = arrOfStrs.map((str) => Number(str));

console.log(arrOfNums); // [ 1, 2, 3, 4 ]

2. String split() Method

We can also split a number into an array with the String split() method. To do this:

  1. Convert the number to a string.
  2. Call the split() method on the string to convert it into an array of stringified digits.
  3. Call the map() method on this array to convert each string to a number.
function splitIntoArray(num) {
  return String(num).split('').map(Number);
}

const arr1 = splitIntoArray(1234);
console.log(arr1); // [ 1, 2, 3, 4 ]

const arr2 = splitIntoArray(4901);
console.log(arr2); // [ 4, 9, 0, 1 ]

The String split() method divides a string into an array of substrings based on the specified separator. We specify an empty string ('') as the separator to split the string into an array of all its characters.

// ['1', '2', '3', '4'];
console.log('1234'.split(''));

We call map() on this string array, passing the Number constructor to convert each element to a number and create a new number array.

// [ 1, 2, 3, 4 ]
console.log(['1', '2', '3', '4'].map(Number));

Tip

This:

// [1, 2, 3, 4]
console.log(['1', '2', '3', '4'].map(Number));

produces the same results as this:

// [ 1, 2, 3, 4 ]
console.log(['1', '2', '3', '4']
  .map((str) => Number(str)));

Although you might prefer to be more explicit with the second way, so you can see exactly what callback arguments you’re passing to Number.

How to Find the Even Numbers in an Array with JavaScript

1. Array filter() Method

To find the even numbers in array with JavaScript, call the filter() method on the array, passing a callback that returns true when the element is even, and false otherwise

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = numbers.filter((num) => num % 2 === 0);

// [10, 8, 18, 6]
console.log(evens);

The filter() method creates a new array with all the elements that pass the test specified in the testing callback function. Only even numbers have a remainder of 0 when divided by 2, so filter() returns an array of all the even numbers in the original array.

Note: filter() preserves the order of the elements from the original array.

2. Array forEach() Method

Alternatively, we can find the odd numbers in an array with the Array forEach() method. We call forEach() on the array, and in the callback, we only add an element to the resulting array if it is even.

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = [];
numbers.forEach((num) => {
  if (num % 2 === 0) {
    evens.push(num);
  }
});

// [ 10, 8, 18, 6 ]
console.log(evens);

3. for…of Loop

We can use the for...of loop in place of forEach() to iterate through the array and find the even numbers.

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = [];
for (const num of numbers) {
  if (num % 2 === 0) {
    evens.push(num);
  }
}

// [ 10, 8, 18, 6 ]
console.log(evens);

4. Traditional for Loop

And we can’t forget the traditional for loop:

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = [];
for (let i = 0; i < numbers.length; i++) {
  const num = numbers[i];
  if (num % 2 === 0) {
    evens.push(num);
  }
}

// [ 10, 8, 18, 6 ]
console.log(evens);

Performance Comparison

Let’s compare the performance of these four methods using an array with 10 million elements (with elements from 1 to 10 million).

const numbers = [...Array(10000000)].map(
  (_, index) => index + 1
);

function measurePerf(label, method) {
  console.time(label);
  method();
  console.timeEnd(label);
}

measurePerf('filter', () => {
  const evens = numbers.filter((num) => num % 2 === 0);
});

measurePerf('forEach', () => {
  const evens = [];
  numbers.forEach((num) => {
    if (num % 2 === 0) {
      evens.push(num);
    }
  });
});

measurePerf('for...of', () => {
  const evens = [];
  for (const num of numbers) {
    if (num % 2 === 0) {
      evens.push(num);
    }
  }
});

measurePerf('for', () => {
  const evens = [];
  for (let i = 0; i < numbers.length; i++) {
    const num = numbers[i];
    if (num % 2 === 0) {
      evens.push(num);
    }
  }
});

Results

Average

  • filter(): 300.216 ms
  • forEach(): 286.516 ms
  • for...of: 298.750 ms
  • for: 137.778 ms

The traditional for loop consistently comes out on top in this comparison. This doesn’t mean you must use it all the time, however. It’s not very often that you need to filter through an array with 10 million elements – in typical use cases, the performance gains you’d get from the for loop will be minuscule. In most scenarios, you’d be better off using filter() due to its greater conciseness and readability, and if you prefer the functional approach, despite its slower speed.

How to Extract a Number from a String in JavaScript

1. String replace() Method

To extract a number from a string in JavaScript, call the replace() method on the string with a regex to replace all the non-digit characters in the original string. For example:

const str = 'The number 345 has three digits';

const replaced = str.replace(/\D/g, '');
console.log(replaced); // 345

The String replace() method returns a new string with the matches of a pattern replaced by a replacement. We pass a regular expression that matches all the non-digit characters so that we can replace them with an empty string ('') to remove them.

The \D regex metacharacter matches any non-digit characters in a string.

The g (global) flag specifies that every occurrence of a non-digit character in the string should be matched by the regex.

If we don’t pass the global flag, only the first non-digit character in the input string will be matched and replaced:

const str = 'The number 345 has three digits';

// No 'g' flag in regex
const replaced = str.replace(/\D/, '');

console.log(replaced); // he number 345 has three digits

2. String match() Method

To extract a number from a string, we can also call the match() method on the string, passing a regex that matches a consecutive sequence of digits. For example:

const str = 'The number 345 has three digits';

const matches = str.match(/\d+/);
const numStr = matches[0];

console.log(numStr); // 345

The String match() method matches a string against a regular expression and returns the results. In our case, the matched number is the first item of the array, so we access the 0 property with bracket notation to get it.

The \d metacharacter is used to find a digit in a string. We add the + to \d in order to find a consecutive sequence of digits.

This second method is better when trying to extract each number in the string separately, as it treats a consecutive sequence of digits as a separate match. To extract each number separately, we’ll need to add the g flag:

const str = 'The numbers 345 and 847 have three digits';

const matches = str.match(/\d+/g);
console.log(matches); // [ '345', '847' ]

Note

When no digits can be found, the match() method will return null:

const str = 'There are no numbers in this string';

const matches = str.match(/\d+/g);
console.log(matches); // null

How to Add Hours to a Date in JavaScript

In this article, we’re going to learn how to easily add number of hours to a Date object in JavaScript.

1. Date setHours() and getHours() methods

To add hours to a Date in JavaScript:

  1. Call the getHours() on the Date to get the hours.
  2. Add the hours.
  3. Pass the sum to the setHours() method.

For example:

function addHours(date, hours) {
  date.setHours(date.getHours() + hours);

  return date;
}

const date = new Date('2022-05-15T12:00:00.000Z');

const newDate = addHours(date, 5);

console.log(newDate); // 2022-05-15T17:00:00.000Z

The Date getHours() method returns a number between 0 and 23 that represents the hours of a particular date.

The Date setHours() method sets the hours of a date to a specified number.

If the hours added would increase the day, month, or year of the DatesetHours() will automatically update the date information to reflect this.

// 11 PM on June 17, 2022
const date = new Date('2022-06-17T23:00:00.000Z');

date.setHours(date.getHours() + 4);

// 3 AM on June 18, 2022 (next day)
console.log(date); // 2022-06-18T03:00:00.000Z

In this example, increasing the hours of the date by 4 moves the day forward to June 18, 2022.

Avoid side effects

The setHours() method mutates the Date object it is called on. This introduces a side effect into our addHours() function. To make a pure function, create a copy of the Date and call setHours() on this copy, instead of the original. For example:

function addHours(date, hours) {
  // πŸ‘‡ Make copy with "Date" constructor.
  const dateCopy = new Date(date);

  dateCopy.setHours(dateCopy.getHours() + hours);

  return dateCopy;
}

const date = new Date('2022-05-15T12:00:00.000Z');

const newDate = addHours(date, 2);
console.log(newDate); // 2022-05-15T14:00:00.000Z

// πŸ‘‡ Original not modified
console.log(date); // 2022-05-15T12:00:00.000Z

Tip: Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about, as they always give the same output for a particular input. This makes it a good practice to limit the number of side effects in your code.

2. date-fns addHours() function

Alternatively, you can use the addHours() function from the date-fns NPM package to quickly add hours to a Date. It works like our pure addHours() function.

import { addHours } from 'date-fns';

const date = new Date('2022-05-15T12:00:00.000Z');

const newDate = addHours(date, 4);
console.log(newDate); // 2022-05-15T16:00:00.000Z

// Original not modified
console.log(date); // 2022-05-15T12:00:00.000Z

How to Get the Last N Characters of a String in JavaScript

To get the last N characters of a string in JavaScript, call the slice() method on the string, passing -N as an argument. For example, str.slice(-3) returns a new string containing the last 3 characters of str.

const str = 'Coding Beauty';

const last3 = str.slice(-3);
console.log(last3); // uty

const last6 = str.slice(-6);
console.log(last6); // Beauty

const last10 = str.slice(-10);
console.log(last10); // ing Beauty

The String() slice() method returns the portion of a string between the start and end indexes, which are specified by the first and second arguments respectively. When we only specify a start index, it returns the entire portion of the string after this start index.

When we pass a negative number as an argument, slice() counts backward from the last string character to find the equivalent index. So passing -N to slice() specifies a start index of str.length - N.

const str = 'Coding Beauty';

const last6 = str.slice(-6);
console.log(last6); // Beauty

const last6Again = str.slice(str.length - 6);
console.log(last6Again); // Beauty

Tip

If we try to get more characters than the string contains, slice() returns the entire string instead of throwing an error.

const str = 'Coding Beauty';

const last50 = str.slice(-50);
console.log(last50); // Coding Beauty

In this example, we tried to get the last 50 characters of the string by passing -50 as the first argument, but the string 'Coding Beauty' contains only 13 characters. Hence, we get the entire string from slice().

Note

We can use substring() in place of slice() to get the first N characters of a string:

const str = 'Coding Beauty';

const last3 = str.substring(str.length - 3);
console.log(last3); // uty

However, we have to manually calculate the start index ourselves with str.length - N, which makes the code less readable. This is because unlike slice(), substring() uses 0 as the start index if a negative number is passed.

const str = 'Coding Beauty';

// -3 is negative, uses 0 instead
const notLast3 = str.substring(-3);

console.log(notLast3); // Coding Beauty