Programming
Concise example of some JS idioms.
function insertionSort(arr) {
const n = arr.length;
for (let i = 1; i < n; i++) {
for (let j = i; j > 0 && arr[j] < arr[j-1]; j--) {
// destructuring assignment: note square brackets
[arr[j], arr[j-1]] = [arr[j-1], arr[j]];
}
}
}
function main() {
function randint(lo, hi) {
return () => lo + Math.floor((Math.random() * (hi - lo)));
}
const n = 10;
console.log([...Array(10).keys()]);
let test = Array(n).fill().map(randint(0, 10));
console.log(`Before: ${test}`);
insertionSort(test);
console.log(`After : ${test}`);
}