Skip to content

Instantly share code, notes, and snippets.

@0x04
Created December 17, 2013 19:38
Show Gist options
  • Save 0x04/8011263 to your computer and use it in GitHub Desktop.
Save 0x04/8011263 to your computer and use it in GitHub Desktop.
(Zero)fill
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>(Zero)fill</title>
</head>
<body>
<script type="text/javascript">
/**
* (Zero)fill
* @creator Oliver Kühn (@0x04)
* @created 2013-12-17
*
* @param {String} value
* @param {Number} length
* @param {String} character
* @param {Boolean} suffix
* @return {String}
*/
function fill(value, length, character, suffix)
{
return [
// Create the fillment string
new Array(length + 1)
.join(character)
.substr(0, length - value.length),
// Our target value
value
// Reverse value with fillment or not
][ suffix ? 'reverse' : 'concat' ]()
// Finally just return a string
.join('');
}
console.group('test `fill`');
console.time('test');
// Test
console.assert(fill('', 6, '0') == '000000');
console.assert(fill('f', 6, '0') == '00000f');
console.assert(fill('ff', 6, '0') == '0000ff');
console.assert(fill('fff', 6, '0') == '000fff');
console.assert(fill('ffff', 6, '0') == '00ffff');
console.assert(fill('fffff', 6, '0') == '0fffff');
console.assert(fill('ffffff', 6, '0') == 'ffffff');
// Suffixed
console.assert(fill('', 6, '0', true) == '000000');
console.assert(fill('f', 6, '0', true) == 'f00000');
console.assert(fill('ff', 6, '0', true) == 'ff0000');
console.assert(fill('fff', 6, '0', true) == 'fff000');
console.assert(fill('ffff', 6, '0', true) == 'ffff00');
console.assert(fill('fffff', 6, '0', true) == 'fffff0');
console.assert(fill('ffffff', 6, '0', true) == 'ffffff');
console.timeEnd('test');
console.groupEnd('test `fill`');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment