DEV Community

Cover image for BubbleSort en Typescript
Ger Moren
Ger Moren

Posted on

4 5

BubbleSort en Typescript

BubbleSort in Javascript

NAMESPACES

Se crea el namespace MathUtils con los distintos types auxiliares para el método BubbleSort:

Num, Length, Push NTuple and Add types

En el caso de la resta importa el orden en que se reciben los paramentos, por este motivo el primer parámetro debe ser mayor o igual que el segundo:
Substract type

Si queremos comparar 2 números en Typescript, los símbolos "<" y
">" no son validos
type isMinor = 1 > 2 ? true : false;
por este motivo vamos a crear el type GreaterComparison
Type GreatComparison

BUBBLE SORT
Ayudándonos del namespace MathUtils definido anteriormente procedemos a definir el type BubbleSort el cual recibe un array como primer parámetro y una variable auxiliar "actual".
Si el array tiene un solo elemento se retorna el mismo array.

Caso contrario extendemos un array en el que se infieren 3 elementos, los números a comparar y lo que queda del resto.

Se llama recursivamente al type BubbleSort.

Bubble Sort Method

type example1 = BubbleSort<[234, 43, 55, 63, 5, 6, 235, 547]>;
// [ 5, 6, 43, 55, 63, 234, 235, 547]
type example2 = BubbleSort<[5, 2, 4, 6, 1, 3]>;
// [1, 2, 3, 4, 5, 6]
type example3 = BubbleSort<[1]>;
// [1]
type example4 = BubbleSort<[]>;
// []
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs