Skip to content

Instantly share code, notes, and snippets.

@LeaVerou
Created December 28, 2014 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeaVerou/adbc2e4750ad809b6aef to your computer and use it in GitHub Desktop.
Save LeaVerou/adbc2e4750ad809b6aef to your computer and use it in GitHub Desktop.
Better (?) weight matching when desired weight is unavailable
/*
* See www-style
* @param req: Desired weight. A multiple of 100 in [100-900]
* @param available: An array of multiples of 100 in [100-900]
* @return The weight picked or -1 if falling back is better
* Call like matchWeight(400, [100, 600, 900])
*/
function matchWeight(req, available) {
if (available.indexOf(req) > -1) {
return req;
}
for (o = -100; Math.abs(o) <= 300; o = -o - (o < 0? 0 : 100)) {
if (available.indexOf(req + o) > -1) {
return req + o;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment