Last active
August 29, 2015 14:05
-
-
Save thinkt4nk/bf77642b2c2ff6901620 to your computer and use it in GitHub Desktop.
Even, whole element width with even, whole margin
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
var fullWidth = 290 | |
var numberOfElements = 7 | |
var positionOffset = 0 | |
process.argv.forEach(function(arg) { | |
var offsetRegexp = /--offset=(\d+)/ | |
if (offsetRegexp.test(arg)) | |
positionOffset = parseInt(arg.replace(offsetRegexp, '$1')) | |
}) | |
var elementWidth = findWidth(fullWidth, numberOfElements) | |
var margin = getMargin(fullWidth, numberOfElements, elementWidth) | |
var message = 'Could not find an even width for ' + numberOfElements + ' elements in a space with width of ' + fullWidth | |
if (margin != null) | |
message = fullWidth + ' is evenly distributed among ' + numberOfElements + ' elements sharing width of ' + elementWidth + ', with a margin of ' + margin | |
console.log(message) | |
var positioning = [] | |
for (var i = 0; i < numberOfElements; i++) { | |
var relativePosition = ((elementWidth * i) + (margin * i)) | |
positioning.push(positionOffset + relativePosition) | |
} | |
console.log('elements begin at positions: ', positioning) | |
function findWidth(fullWidth, numberOfElements, currWidth) { | |
currWidth = currWidth || Math.floor((fullWidth / numberOfElements)) | |
if (currWidth < 0) | |
return null | |
currMargin = getMargin(fullWidth, numberOfElements, currWidth) | |
if ((currMargin % 1) !== 0) | |
return findWidth(fullWidth, numberOfElements, (currWidth - 1)) | |
return currWidth | |
} | |
function getMargin(fullWidth, numberOfElements, elementWidth) { | |
return ((fullWidth - (numberOfElements * elementWidth)) / (numberOfElements - 1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment