Get Programming with JavaScript - Listing 7.06
Listing 7.06 - Using Math.min and Math.max to constrain an argument
JS Bin
var line = function (lineLength) {
var line = "========================================";
lineLength = Math.max(0, lineLength);
lineLength = Math.min(40, lineLength);
return line.substr(0, lineLength);
};
console.log(line(30));
console.log(line(40));
console.log(line(50));
Further Adventures
Listing 7.06 - Using Math.min and Math.max to constrain an argument - Task 1
- Test line lengths from -20 to 60 in steps of 10.
var line = function (lineLength) {
var line = "========================================";
lineLength = Math.max(0, lineLength);
lineLength = Math.min(40, lineLength);
return line.substr(0, lineLength);
};
console.log(line(-20));
console.log(line(-10));
console.log(line(0));
console.log(line(10));
console.log(line(20));
console.log(line(30));
console.log(line(40));
console.log(line(50));
console.log(line(60));
Listing 7.06 - Using Math.min and Math.max to constrain an argument - Task 2
- Define a spaces function that returns a string made up of a specified number of space characters. The line of spaces returned can have a length between 0 and 40.
var spaces = function (lineLength) {
// create a string made up of 40 spaces
var line = " ";
// ensure lineLength is between 0 and 40 inclusive
lineLength = Math.max(0, lineLength);
lineLength = Math.min(40, lineLength);
// return a substring of the specified length
return line.substr(0, lineLength);
};
Listing 7.06 - Using Math.min and Math.max to constrain an argument - Task 3
- Add an emptyBox function that draws an empty box of specified width and height 5.
var line = function (lineLength) {
var line = "========================================";
lineLength = Math.max(0, lineLength);
lineLength = Math.min(40, lineLength);
return line.substr(0, lineLength);
};
var spaces = function (lineLength) {
var line = " ";
lineLength = Math.max(0, lineLength);
lineLength = Math.min(40, lineLength);
return line.substr(0, lineLength);
};
var emptyBox = function (width) {
// top border
var box = "\n" + line(width);
// middle section of height 3
box += "\n=" + spaces(width - 2) + "=";
box += "\n=" + spaces(width - 2) + "=";
box += "\n=" + spaces(width - 2) + "=";
// bottom border
box += "\n" + line(width);
box += "\n";
console.log(box);
};
// test the emptyBox function
emptyBox(12);