TypeScript Bubble Sort and Classes
Sat Nov 21 2020 00:37:48 GMT+0000 (UTC)
Posted by
@narro
#typescript
// Bubble sorting using most of the important features in TypeScript
//* index.ts
import { Sorter } from './Sorter';
import { NumbersCollection } from './NumbersCollecton';
// Passing object into helper function to prepare variable for sorter when data is an array
const numbersCollection = new NumbersCollection([10, 3, -5, 0])
// Passing in object now instead of raw data
const sorter = new Sorter(numbersCollection)
sorter.sort()
console.log(numbersCollection.data)
//* Sorter.ts
import { NumbersCollection } from './NumbersCollecton';
export class Sorter {
constructor(public collection: NumbersCollection) {}
sort(): void {
const { length } = this.collection
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
if (this.collection.compare(j, j + 1)) {
this.collection.swap(j, j+1)
}
// Only going to work if collecton is a string
// If collection is a string, do this instead
// ~~~logic to compare and swap characters in a string
}
}
}
}
//* NumbersCollection.ts
/* Class Structure: */
// File: NumbersCollection.ts
// Class: NumbersCollection {
// Constructor: constructor(permissions, vars: types) {}
// Function(s) function(): type {
// function body
// } //close function
// } // Close Class
export class NumbersCollection {
// Require an array of numbers to be passed in and instantiated
constructor(public data: number[]) {}
// Need to get length of array
get length(): number {
return this.data.length
}
// decide if we need to swap 2 elements in a pair (bubble sort)
/* is -1 > 0 ? If so, swap them
/ |
/ |
[-1] [0] [5] [10] */
compare(leftIndex: number, rightIndex: number): boolean {
return this.data[leftIndex] > this.data[rightIndex]
}
swap(leftIndex: number, rightIndex: number): void {
const leftHand = this.data[leftIndex]
this.data[leftIndex] = this.data[rightIndex]
this.data[rightIndex] = leftHand
}
}
// const collection = new NumbersCollection([1,2,3])
// // since 'get' was used, length doesn't need to be called as a function (ex: collection.length())
// collection.length
content_copy Copy
TypeScript class. Good example for TS Class structure demonstrated on a bubble sort function
This example only accepts an array of numbers, see other snippet for a version that can differentiate between an array of Numbers and strings
https://www.udemy.com/course/typescript-the-complete-developers-guide/learn/lecture/15066674#questions/13040850/
Comments