Last active
August 30, 2015 23:42
-
-
Save Sufuninja/261a4fc008e080d3d632 to your computer and use it in GitHub Desktop.
Practice functions. A basic rewriting of the .sort() method in JavaScript
This file contains 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
/* This is my version of sort. It is cluncky and took me far too | |
long to complete. But now it works!...Thanks to splice().*/ | |
function sort(array){ | |
var currentLargest = array[0]; | |
// store sorted values to be itterated though if item is < currentLargest | |
var tempArray = []; | |
/* Updated final array to be returned. I was not sure if trying to itterate through, | |
tempArray while changing it, would cause unpredictable results so I tried this.*/ | |
var finalArray = []; | |
array.forEach(function(item, index, array){ | |
//start off with the first value to compair to | |
if(index === 0){ | |
tempArray.push(item); | |
// If item is bigger than currentLargest push it, and update currentLargest | |
}else if(item >= currentLargest){ | |
currentLargest = item; | |
tempArray.push(item); | |
//update finalArray to reflect tempArray | |
finalArray = tempArray | |
// If item is smaller find out where it goes in the array | |
}else { | |
for(var j = 0; j < tempArray.length; j++){ | |
// if item is smaller, put it in front, if not try next value in tempArray. | |
if(item <= tempArray[j]){ | |
finalArray.splice(j, 0, item); | |
tempArray = finalArray; | |
break; | |
} | |
} | |
} | |
});return finalArray; | |
}; | |
console.log(sort([2, 4, 3, 7, 12, 76, 45, 122, 3, 4, 4, 45, 56, 3])); | |
//====================================== | |
// ANOTHER VERSION OF SORT() | |
//====================================== | |
var nums = [2, 34, 45, 3]; | |
// Finds the smallest number in an array | |
function arrayMin(array){ | |
return Math.min.apply(Math, array); | |
}; | |
// Finds the index of the smallest number in and array | |
var indexOfMin = function(array){ | |
return array.indexOf(arrayMin(array)); | |
}; | |
// Uses the above funcitons to make a new array by finding the lowest number first, | |
//putting it into a new array then erasing it from the old one. | |
var reOrder = function(array, index, min){ | |
newOrder = []; | |
while(array.length > 0){ | |
newOrder.push(min(array)); | |
array.splice(index(array), 1); | |
};return console.log("New array: " + newOrder + " Original array: " + array); | |
}; | |
//testing the helpers | |
//console.log(arrayMin(nums)); | |
//console.log(indexOfMin(nums)); | |
reOrder(nums, indexOfMin, arrayMin); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment