// 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
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter