Skip to content

Instantly share code, notes, and snippets.

@stackptr
Created September 8, 2014 22:08
Show Gist options
  • Save stackptr/e7d6f7947e74be24f38f to your computer and use it in GitHub Desktop.
Save stackptr/e7d6f7947e74be24f38f to your computer and use it in GitHub Desktop.
LessThan3 programming challenge
// Compare function for sort:
// Move 'jack' forward first, then 'jill' if no 'jack'; leave other values unsorted
function compare(a, b){
if (a === 'jack'){
return -1;
} else if (b === 'jack') {
return 1;
} else if (a === 'jill') {
return -1;
} else if (b === 'jill') {
return 1;
} else {
return 0;
}
}
// Define test cases and expected outputs
var testCases = [
['bob', 'jill', 'jack', 'amanda'],
['bob', 'jill', 'amanda'],
['bob', 'jack', 'jill', 'jack', 'amanda']
];
var expectedOutputs = [
['jack', 'jill', 'bob', 'amanda'],
['jill', 'bob', 'amanda'],
['jack', 'jack', 'jill', 'bob', 'amanda']
];
// Perform tests
testCases.forEach(function(testCase, i){
console.log('Test case ' + i);
console.log('input: ' + testCase.join(', '));
testCase.sort(compare); // Sort in place
console.log('output: ' + testCase.join(', '));
if (testCase.join('') === expectedOutputs[i].join('')){
console.log("=> Pass");
} else {
console.log("=> Fail");
}
console.log('');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment