Last active
November 20, 2016 22:32
-
-
Save narainsagar/b42e5a84f098765c917cbf4a351e6709 to your computer and use it in GitHub Desktop.
Order Array of data based on activeIndex and clickedIndex elements.. (i.e., Images slider example)
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
/** | |
* Order Array of data based on single data... | |
* IDEA: | |
In Images Slider example we'd have collection of images data and one one image will be shown as default active (to be shown always). | |
Now when we click on anyother image that will be active and other images will be ordered according. we will be order all images in a way that | |
all images will be viewing in cycle (from both sides). | |
**/ | |
/** | |
* Usage Examples: | |
* var b = orderArray([1, 2, 3], 2); | |
* var b = orderArray([1, 2, 3], 2, 0); | |
**/ | |
/** | |
* @params: | |
* dataArray : Array | |
* clickedIndex: Number (should be >= 0) | |
* activeIndex: Number (should be >= 0) | |
* @return : Array | |
**/ | |
function orderArray(dataArray, clickedIndex, activeIndex) { | |
if(!Array.isArray(dataArray) || typeof clickedIndex === "undefined" || clickedIndex >= dataArray.length) { | |
throw new Error('Wrong parameters..'); | |
return; | |
} | |
// if activeIndex is not set then middle element index of dataArray will be the default activeIndex. | |
if (typeof activeIndex === "undefined") activeIndex = Math.ceil(dataArray.length / 2) - 1; | |
var toShiftCount = clickedIndex - activeIndex; | |
return (toShiftCount < 0) ? dataArray.splice(toShiftCount).concat(dataArray) : dataArray.concat(dataArray.splice(0, toShiftCount)); | |
} | |
/** | |
* Created By: Narain Sagar (9) | |
* Date: November 21, 2016 | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment