Sorting in TypeScript

import { sort } from 'lodash';

// TypeScript's built-in sorting is in-place and doesn't work
// with all data types, so we'll use lodash for this example

// Sorting functions work for any comparable type
const strs: string[] = ["c", "a", "b"];
sort(strs);
console.log("Strings:", strs);

// An example of sorting numbers
const ints: number[] = [7, 2, 4];
sort(ints);
console.log("Numbers:", ints);

// We can also check if an array is already in sorted order
const isSorted = (arr: any[]): boolean => {
    return arr.every((v, i, a) => !i || a[i-1] <= v);
};

console.log("Sorted:", isSorted(ints));

In TypeScript, we don’t have a built-in slices package like in the original example. Instead, we’re using the lodash library, which provides a sort function that works similarly. Here’s an explanation of the TypeScript code:

  1. We import the sort function from lodash. This function can sort arrays of various types.

  2. We define an array of strings and sort it using sort(strs). The sort function modifies the original array.

  3. We do the same with an array of numbers.

  4. To check if an array is sorted, we define a custom isSorted function. This function uses the every method to check if each element is greater than or equal to the previous one.

  5. Finally, we use our isSorted function to check if the ints array is sorted.

To run this TypeScript code, you would need to have TypeScript and lodash installed. You can compile and run it like this:

$ tsc sorting.ts
$ node sorting.js
Strings: [ 'a', 'b', 'c' ]
Numbers: [ 2, 4, 7 ]
Sorted: true

This TypeScript code demonstrates sorting and checking if an array is sorted, similar to the original example. Note that TypeScript’s type system ensures type safety, so we’ve explicitly typed our arrays as string[] and number[].