Last active
July 15, 2017 17:57
-
-
Save mattpodwysocki/5414036 to your computer and use it in GitHub Desktop.
Implementation of QuickSort using ES6 features
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
// Using comprehensions | |
function sort(arr) { | |
var pivot, t; | |
if (arr.length === 0) { | |
return []; | |
} | |
[pivot, t] = [arr[0], arr.slice(1)]; | |
return sort([x for (x of t) if x < pivot]) | |
.concat(pivot) | |
.concat(sort([x for (x of t) if x >= pivot])); | |
} | |
// Using arrows with filter | |
function sort(arr) { | |
var pivot, t; | |
if (arr.length === 0) { | |
return []; | |
} | |
[pivot, t] = [arr[0], arr.slice(1)]; | |
return sort(t.filter(x => x < pivot)) | |
.concat(pivot) | |
.concat(sort(t.filter(x => x >= pivot))); | |
} | |
// Erlang equivalent | |
sort([Pivot|T]) -> | |
sort([ X || X <- T, X < Pivot]) ++ | |
[Pivot] ++ | |
sort([ X || X <- T, X >= Pivot]); | |
sort([]) -> []. |
Sure, I suppose I could have used arrow functions with filter for each instead of comprehensions
Updated with alternate version. A better way of destructuring though?
you don't really need concat neater.
function sort(arr) {
if (!arr.length) {
return [];
}
let pivot = arr.pop();
return [
...sort([x for (x of arr) if x < pivot]),
pivot,
...sort([x for (x of arr) if x >= pivot])
]
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hmm...