Created
July 24, 2015 09:12
-
-
Save DenisIzmaylov/284f90c0e345648d355b to your computer and use it in GitHub Desktop.
Offset (with limit) calculation / validation
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
function offset(count, offset, limit) { | |
const finalOffset = Math.max(Math.min(count, offset), 0); | |
const remainedCount = Math.min(count, count - finalOffset); | |
const finalCount = (typeof limit === 'number') ? Math.min(limit, remainedCount) : remainedCount; | |
return { offset: finalOffset, finalCount: finalCount }; | |
} | |
console.log(offset(10, 0)); // {"offset":0,"finalCount":10} | |
console.log(offset(10, 4)); // {"offset":4,"finalCount":6} | |
console.log(offset(10, 10)); // {"offset":10,"finalCount":0} | |
console.log(offset(10, 10)); // {"offset":10,"finalCount":0} | |
console.log(offset(10, 15)); // {"offset":10,"finalCount":0} | |
console.log(offset(10, 10)); // {"offset":10,"finalCount":0} | |
console.log(offset(10, 3, 5)); // {"offset":3,"finalCount":5} | |
console.log(offset(10, 2, 10)); // {"offset":2,"finalCount":8} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment