10 One-Liner Utility methods in TypeScript/JavaScript

10 One-Liner Utility methods in TypeScript/JavaScript

Typescript/JavaScript, Code Snippets to increase productivity in one line

Sometimes you have some duplicate code that you want to share across the project. It does not belong to some particular type. Those type of function and class called utility methods or utility class. Utility methods can be written in one single file or they can be split into multiple files, base on their categorization. I personally prefer, I util folder with multiple files. However, I use a single file for all common small utility functions.

Note: All code example has written in TypeScript. You can use TypeScript Playground to convert TS to JS code. Another thing to note, Sample Example Codes are actually not the one-liner. But all code has only one line logical block.

How to create a reusable utility module

If you are using TypeScript or Babel in your project, You can use the ES6 module out of the box.

// util/draw.ts

export const name = 'square';

export function area(length: number, breadth: number) {
  return length * breadth

However, in traditional node.js, ES6 import and export are not supported out of the box. You can use module.exports/exports to export method or class.

// util/draw.js

exports.name = 'square';

exports.area = (length, breadth) => {
  return length * breadth

Once you have the setup ready. You can use the below function in your utility file.

1. Array to CSV

Converting an array to CSV is a very common operation in the frontend. We do not want to create a server API to perform such a small logical CSV generation. Before generating a CSV file, We need to convert the array to a CSV string. The below util method can help to generate CSV string.

const arrayToCSV = (arr: (string | number)[][], delimiter = ",") =>
    .map((v) =>
        .map((x) => (typeof x === "string" ? `"${x.replace(/"/g, '""')}"` : x))

How to use:

  ["a", '"b" great'],
  ["c", 3.1415],
]); // '"a","""b"" great"\n"c",3.1415'

2. Capitalize

Capitalizes the first letter of a string. you can pass lowerRest, to convert rest characters in lowercase.

const capitalize = (str: string = "", lowerRest = false): string =>
  str.slice(0, 1).toUpperCase() +
  (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));

How to use:

capitalize("fooBar"); // 'FooBar'
capitalize("fooBar", true); // 'Foobar'

Modified version(using regex, replace)

const capitalizeEveryWord = (str = "") =>
  str.replace(/\b[a-z]/g, (char) => char.toUpperCase());

How to use:

capitalizeEveryWord("hello world!");  // 'Hello World!'

3. Cast/Convert into Array

Casts the provided value as an array if it's not one.

export const castArray = (val: any): any[] =>
  Array.isArray(val) ? val : [val];

How to use:

castArray("foo");  // ['foo']
castArray([1]);  // [1]

4. Create chunks of Array

Chunks an array into smaller arrays of a specified size.

export const chunk = (arr: any[], size: number) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (_: any, i: number) =>
    arr.slice(i * size, i * size + size)

How to use:

chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]

5. Create a compact Array by removing falsy values

const compact = (arr: any[]) => arr.filter(Boolean);

How to use:

compact([0, 1, false, 2, "", 3, "a", Number("e") * 23, NaN, "s", 34]); // [ 1, 2, 3, 'a', 's', 34 ]

6. String contains

Returns true if given string s1 contains s2. Compare is case insensitive.

const contains = (s1: string, s2: string = "") =>
  s1.toLowerCase().indexOf(s2.toLowerCase()) !== -1;

How to use:

contains("Text1", "Ext"); // true
contains("Text1", "et"); // false

7. Convert CSV string to 2D Array

Converts a comma-separated values (CSV) string to a 2D array.

const CSVToArray = (data: string, delimiter = ",", omitFirstRow = false) =>
    .slice(omitFirstRow ? data.indexOf("\n") + 1 : 0)
    .map((v) => v.split(delimiter));

How to use:

CSVToArray("a,b\nc,d"); // [['a','b'],['c','d']];
CSVToArray("a;b\nc;d", ";"); // [['a','b'],['c','d']];
CSVToArray("col1,col2\na,b\nc,d", ",", true); // [['a','b'],['c','d']];

8. Deep Flatten Array

const deepFlatten = (arr: any[]): any[] => {
  if (typeof Array.prototype.flat !== "undefined") return arr.flat(Infinity);
  return [].concat(
    ...arr.map((v: any) => (Array.isArray(v) ? deepFlatten(v) : v))

How to use:

deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]
deepFlatten([1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note: You can also use ES2017 API to flatten Array.

[1, [2], [[3], 4], 5].flat(Infinity)

9. Ellipsis or Truncates Strings

Truncates a string up to a specified length.

Determine if the string's length is greater than num. Return the string truncated to the desired length, with '...' appended to the end of the original string.

const ellipsis = (str: string, num: number = str.length, ellipsisStr = "...") =>
  str.length >= num
    ? str.slice(0, num >= ellipsisStr.length ? num - ellipsisStr.length : num) +
    : str;

How to use:

ellipsis("boomerang", 5, ".."); // "boo.."

ellipsis("boomerang"); // "boomer..."

ellipsis("boomerang", undefined, "♦♦♦"); // "boomer♦♦♦"

10. Group data by the key or function

Groups the elements of an array based on the given function.

Use Array.prototype.map() to map the values of an array to a function or property name. Use Array.prototype.reduce() to create an object, where the keys are produced from the mapped results.

type MapFunc<T = any> = (val: T, index?: number, arr?: T[]) => T;

const groupBy = <T = any>(arr: T[], fn: MapFunc<T> | string) =>
  arr.map(isString(fn) ? (val: any) => val[fn] : fn).reduce((acc, val, i) => {
    acc[val] = (acc[val] || []).concat(arr[i]);
    return acc;
  }, {});

How to use:

groupBy([6.1, 4.2, 6.3], Math.floor); // {4: [4.2], 6: [6.1, 6.3]}
groupBy(["one", "two", "three"], "length"); // {3: ['one', 'two'], 5: ['three']}


After writing the 10 method example, I realized that I could not cover all the One-Liner util in one post. Same time I could not pick the best of 10 among them all. So I will try to cover the rest in another Article. If your willing to spend some spare time. You can find your best utility method here on my website 30 Seconds of Typescript.

Please let me know your best in the comments. If you have your own version of the one-liner. Please do let me know, I will include it on my website as well as in my next article.

Thanks for reading. If you like, Please share and react to my article.

Did you find this article valuable?

Support Deepak Vishwakarma by becoming a sponsor. Any amount is appreciated!