function padToFour(number) {
if (number<=9999) { number = ("000"+number).slice(-4); }
return number;
}
Something like that?
Bonus incomprehensible-but-slicker single-line ES6 version:
let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;
ES6isms:
let
is a block scoped variable (as opposed to var
’s functional scoping)
=>
is an arrow function that among other things replaces function
and is prepended by its parameters
- If a arrow function takes a single parameter you can omit the parentheses (hence
number =>
)
- If an arrow function body has a single line that starts with
return
you can omit the braces and the return
keyword and simply use the expression
- To get the function body down to a single line I cheated and used a ternary expression