Skip to main content

Solutions: Object Oriented JavaScript: 3. Functions


Chapter 3: Functions

1. Write a function that converts a hexadecimal color, for example blue "#0000FF", into its RGB representation "rgb(0,0,255)". Name your function getRGB() and this it with this code:
  var a = getRGB("#00FF00");
  a;       
  rgb(0,255,0)

  //Simple logic for getRgb()  
  var getRGB = function f(hexColor) {
    var result = "rgb(";   
    result += parseInt("0x"+hexColor[1]+hexColor[2]) + ", ";
    result += parseInt("0x"+hexColor[3]+hexColor[4]) + ", ";
    result += parseInt("0x"+hexColor[5]+hexColor[6]) + ")";
    return result;
  }    

  >> getRGB("#0000FF");
  "rgb(0, 0, 255)"

  >> getRGB("#00FF00");
  "rgb(0, 255, 0)"


2. What does each of these lines print in the console?

    >> parseInt(1e1)
    10    //1e1 is evaluated first

    >> parseInt('1e1')
    1  

    >> parseFloat('1e1')
    10    //parseFloat evaluates exponential in string
  
    >> isFinitie(0/10)
    true

    >> isFinite(20/0)
    false

    >> isNaN(parseInt(NaN));
    true


3. What does the following code alert()?
  >> var a = 1;
  function f() {
    var a = 2;
    function n() {
      alert(a);
    }
    n();
  }
  f();

    // It alerts 2. alert(a) has first access to the local variable a in f() which is defined as 2.

4. All these examples alert "Boo!". Can you explain why?

4.1  var f = alert; 
     eval('f("Boo!")');

f is assigned the function alert and eval executes the script in string by passing 'Boo!' as parameter.

4.2  var e;
     var f = alert;
     eval('e=f')('Boo!");
f is assigned the function alert and eval further assigns alert to e and executes the script in string by passing 'Boo!' as parameter.

4.3  (
       function() {
         return alert;
       }
     )() ('Boo!');

function() is a self invoking anonymous function that returns the method alert which is executed immediately by passing 'Boo!' as parameter.

Next: 4. Objects coming soon ...

Comments

  1. Please upload chapter 4 solutions i need it....

    ReplyDelete
  2. CHAPTER 4: Objects

    4 & 5

    function MyString(string) {
    this.length = 0;
    for (var i in string) {
    this[i] = string[i];
    this.length++;
    }
    this.toString = function() {
    return string;
    }
    this.valueOf = this.toString;
    this.charAt = function(value) {
    return this[window.isNaN(value) ? 0 : value];
    }
    this.concat = function() {
    var wynik = string;
    for (var i in arguments) {
    wynik += arguments[i];
    }
    return wynik;
    }
    this.slice = function(start,end) {
    var wynik = '';
    start = start < 0 ? this.length+start : start;
    end = end < 0 ? this.length+end : end;
    for (i=start; i<end; i++) {
    wynik+=this[i];
    }
    return wynik;
    }
    this.split = function(reg) {
    var arr=[];
    var j=0;
    for (var i in string) {
    if (this[i] == reg) {
    arr[++j]="";
    continue;
    }
    arr[j] = typeof arr[j] === "undefined" ? ""+ this[i] : arr[j] + this[i];
    if (reg == "")
    j++;
    }
    return arr;
    }
    this.reverse = function() {
    var wynik = this.split("");
    return wynik.reverse().join("");
    }
    }

    ReplyDelete
  3. 6

    function MyArray() {
    this.length = 0;
    for (var i in arguments) {
    this[i] = arguments[i];
    this.length++;
    }
    this.join = function(reg) {
    var wynik = "";
    for (var j = 0; j < this.length; j++) {
    wynik += this[j] + (j==this.length-1 ? "": reg);
    }
    return wynik;
    }
    this.toString = function() {
    return this.join(",");
    }
    this.push = function () {
    for (var k in arguments) {
    this[this.length++]= arguments[k];
    }
    return this.length;
    }
    this.pop = function() {
    delete this[--this.length];
    return "["+this.toString()+"]";
    }
    }

    ReplyDelete
  4. 7 (sorry for primitive random number generation)

    function MyMath() {
    this.rand = function(min,max,inc) {
    var w = (new Date).valueOf();
    var r = parseFloat(w.toPrecision(10));
    w = ((w - r) > 0 ? w - r : (w - r)*(-2))/999.765758678;
    if (inc !== true) {
    max-=1;
    min+=1;
    }
    var wynik = (parseInt(min) + w*(parseInt(max) - parseInt(min))).toFixed(0);
    return wynik;
    }
    this.max = function(array) {
    var maximum = -Infinity;
    for (var i in array) {
    maximum = (array[i] > maximum) ? array[i] : maximum;
    }
    return maximum;
    }
    this.min = function(array) {
    var minimum = Infinity;
    for (var i in array) {
    minimum = (array[i] < minimum) ? array[i] : minimum;
    }
    return minimum;
    }
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Minimal required code in HTML5

I've encountered this question repeatedly of late. "What are the tags required at bare minimum for a html file?" Earlier there were a bunch of mandatory tags that were required for any html file. At bare minimum, the recommended structure was: (ref: http://www.w3.org/TR/html4/struct/global.html ) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML>   <HEAD>     <TITLE>A small HTML</TITLE>   </HEAD>   <BODY>     <P>Small HTML file!</P>   </BODY> </HTML> Yes, using capitals for the tags was the way to go! Those were the days of the purists and strict was the way to be. Now open your notepad and copy the above code, save the file as old.html and launch it in Chrome or Firefox. You will see only one line "Small HTML file!" shown. Now launch the developer tools in Chrome or Inspect Element in Firefox. Thi...

Using duplicate IDs in HTML

Well today I'm being a bit controversial. Let us see what the HTML5 spec says about unique IDs in a HTML file. The  id  attribute specifies its element's  unique identifier (ID) . The value must be unique amongst all the IDs in the element's  home subtree  and must contain at least one character. The value must not contain any  space characters . An element's  unique identifier  can be used for a variety of purposes, most notably as a way to link to specific parts of a document using fragment identifiers, as a way to target an element when scripting, and as a way to style a specific element from CSS. Yes its been mentioned almost everywhere on the planet that ID must be unique. Now let us look at the below code, Launch dup.css #p2 {   background-color: yellow;  } dup-id.html <!DOCTYPE html> <html>   <head>     <title>Duplicate ID Tester</title> <link rel="stylesh...

Fixing Date, Time and Zone on RHEL 6 command line

Had to fix all time related issues on a remote RHEL 6 server which runs without any windowing system. Plain ol' command line. Documenting steps here for future reference: Check to see if your date and timezone settings are accurate: # date # cat /etc/sysconfig/clock The server I accessed had wrong settings for both the commands. Here are the steps I used to correct: Find out your timezone from the folder /usr/share/zoneinfo # ls /usr/share/zoneinfo Mine was pointing to America/EDT instead of  Asia/Calcutta Update and save the /etc/sysconfig/clock file to # sudo vi /etc/sysconfig/clock ZONE="Asia/Calcutta" UTC=true ARC=false Remove the /etc/localtime # sudo rm /etc/localtime Create a new soft link to your time zone # cd /etc # sudo ln -s /usr/share/zoneinfo/Asia/Calcutta /etc/localtime # ls -al localtime Now it should show the link to your time zone Set your hardware clock to UTC # sudo hwclock --systohc --utc # hwclock --show Update your t...