Get Programming with JavaScript - Listing 7.06

Listing 7.06 - Using Math.min and Math.max to constrain an argument

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

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

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

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);