Created
March 27, 2023 07:38
-
-
Save mike-at-redspace/d3510cd645ab36d24cb780f865ea19b7 to your computer and use it in GitHub Desktop.
Bubble Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const bubbleSortObjects = (arr, key) => { | |
let swapped | |
const swap = i => { | |
;[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]] | |
swapped = true | |
} | |
do { | |
swapped = false | |
for (let i = 0; i < arr.length - 1; i++) { | |
const a = arr[i][key] | |
const b = arr[i + 1][key] | |
switch (typeof a) { | |
case 'string': | |
if (a.localeCompare(b) > 0) { | |
swap(i) | |
} | |
break | |
case 'number': | |
if (a > b) { | |
swap(i) | |
} | |
break | |
default: | |
break | |
} | |
} | |
} while (swapped) | |
return arr | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('bubbleSortObjects', () => { | |
it('should sort an array of objects by a string key', () => { | |
const arr = [ | |
{ name: 'John', age: 28 }, | |
{ name: 'Jane', age: 32 }, | |
{ name: 'Bob', age: 22 } | |
] | |
const key = 'name' | |
const expected = [ | |
{ name: 'Bob', age: 22 }, | |
{ name: 'Jane', age: 32 }, | |
{ name: 'John', age: 28 } | |
] | |
const result = bubbleSortObjects(arr, key) | |
expect(result).toEqual(expected) | |
}) | |
it('should sort an array of objects by a numeric key', () => { | |
const arr = [ | |
{ name: 'Steve', age: 28 }, | |
{ name: 'Jane', age: 32 }, | |
{ name: 'Bob', age: 22 } | |
] | |
const key = 'age' | |
const expected = [ | |
{ name: 'Bob', age: 22 }, | |
{ name: 'Jane', age: 32 }, | |
{ name: 'Steve', age: 28 } | |
] | |
const result = bubbleSortObjects(arr, key) | |
expect(result).toEqual(expected) | |
}) | |
it('should handle arrays with a single element', () => { | |
const arr = [{ name: 'John', age: 28 }] | |
const key = 'name' | |
const expected = [{ name: 'John', age: 28 }] | |
const result = bubbleSortObjects(arr, key) | |
expect(result).toEqual(expected) | |
}) | |
it('should handle empty arrays', () => { | |
const arr = [] | |
const key = 'name' | |
const expected = [] | |
const result = bubbleSortObjects(arr, key) | |
expect(result).toEqual(expected) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment