Forked from anonymous/Is Sorted (2.6) Extra Problems.js
Created
July 31, 2016 19:39
-
-
Save sethschori/98acb9a60c1358285deea93175d41ace to your computer and use it in GitHub Desktop.
https://repl.it/C1TA/81 created by sethopia
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
/* | |
Check if Array is Sorted | |
Complete the function isSorted, which takes an array as inputed and outputs a boolean indicating if the array's contents are in ascending order. | |
isSorted([8,2,3,4]) | |
// -> false | |
isSorted([2,3,4,8]) | |
// -> true | |
*/ | |
function isSorted(arr) { | |
for (var i = 0; i < arr.length - 1; i++) { | |
if (arr[i] > arr[i+1]) return false; | |
} | |
return true; | |
} | |
console.log(isSorted([8,2,3,4])); | |
console.log(isSorted([2,3,4,8])); | |
/* | |
Below is the suggested answer. I wonder which is more efficient? Mine uses 6 lines of code, the suggested one uses 8. | |
The suggested one stringifies and also does a sort. Mine only does one loop, and if the array isn't sorted mine will | |
stop part-way through. So mine might be more efficient. However the biggest advantage that I see of the suggested | |
solution is that the code is more straight forward and clear to understand what's happening, whereas mine is a loop | |
that has a little more cognitive load to work through. | |
*/ | |
//Helper function for sorting | |
function sortNums(a,b) { | |
return a - b; | |
} | |
function isSortedSuggested(arr) { | |
var original = arr.toString() | |
var sorted = arr.sort(sortNums).toString(); | |
return original === sorted; | |
} |
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
Native Browser JavaScript | |
>>> false | |
true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment