Logo
Logo

Programming by Stealth

A blog and podcast series by Bart Busschots & Allison Sheridan.

PBS 19 of X – Some JavaScript Challenges

While recording instalment 18 of the Programming by Stealth series, I promised Allison some challenges to help listeners test and hone their understanding of the core JavaScript language. Since we’ve now covered pretty much the whole language in the series, it’s the perfect time to pause and consolidate that knowledge.

These challenges are designed to be run in the PBS JavaScript Playground. You may also find the PBS JavaScript cheatsheet helpful.

Matching Podcast Episode 449

Listen Along: Chit Chat Across the Pond Episode 449

You can also Download the MP3

Challenge 1 – The 12 Times Tables

Using a loop of your choice, print the 12 times tables from 12 times 1 up to and including 12 times 12.

Challenge 2 – The Fibonacci Series

Write code to print out the Fibonacci series of numbers, stopping after the numbers go above 1,000,000 (you may print one number that is above 1,000,000, but no more).

The first two numbers in the series are 0 and 1. After that, the next number in the series is the sum of the previous two numbers.

Build up your solution in the following way:

  1. Create an array named fibonacci with two initial values – 0, and 1.
  2. Write a while loop that will keep going until the value of the last element of the fibonacci array is greater than 1,000,000. Inside the while loop, do the following:
    1. Calculate the next Fibonacci number by adding the last two elements in the fibonacci array together.
    2. Add this new value to the end of the fibonacci array.
  3. Print the Fibonacci series, one element per line, by converting the fibonacci array into a string separated by newline characters.

Challenge 3 – FizzBuzz

This is a total cliché, and very common as an interview question. It tests if a programmer understands programming basics like loops and conditionals.

Write a program that prints the numbers from 1 to 100. But for multiples of three, print “Fizz” instead of the number. For the multiples of five, print “Buzz”. For numbers which are multiples of both three and five, print “FizzBuzz”.

Challenge 4 – Factorial

Write a function to calculate the factorial of an arbitrary number. Name the function factorial. It’s only possible to calculate the factorial of a whole number greater than or equal to zero. If an invalid input is passed, return NaN.

As a reminder, the factorial of 0 is 1, and the factorial of any positive number, n, is defined as n times the factorial of n - 1.

You can write your solution either using a loop of your choice or using recursion.

Test your function by calculating the factorial of the inputs in the PBS playground. If no inputs are set, print a message telling the user to enter numbers into the inputs.

Challenge 5 – Complex Numbers

Build a prototype to represent a complex number. In case you’re a little rusty on the details, this page offers a really nice explanation of complex numbers. The prototype should be named ComplexNumber.

Build up your solution in the following way:

Step 1

Define a constructor function for your prototype (it must be named the same as the prototype we are building, i.e. ComplexNumber).

  1. For now, the constructor will not take any arguments.
  2. In the constructor, Initialise a key named _real to the value 0.
  3. Also Initialise a key named _imaginary to the value 0.

Step 2

Add a so-called accessor function to the prototype to get or set the real part of the complex number. Name the function real.

  1. If no arguments are passed, the function should return the current value of the _real key.
  2. If there is a first argument, make sure it’s a number. If it’s not, throw an error. If it is, set it as the value of the _real key, and return a reference to the current object (i.e. this). (This will enable a technique known as function chaining, which we’ll see in action shortly.)

Step 3

Create a similar accessor function for the imaginary part of the complex number, and name it imaginary.

Step 4

Add a function to the prototype named toString. This function should return a string representation of the complex number. The rendering should adhere to the following rules:

  1. In the general case, where both real and imaginary parts are non-zero, return a string of the following form: '(2 + 3i)'. If the imaginary number is negative, change the + to a -.
  2. If the imaginary part is exactly 1, just show it as i.
  3. If either of the parts are equal to zero, omit the parentheses.
  4. If the real and imaginary parts are both zero, just return the string '0'.
  5. If only the imaginary part is zero, return just the real part as a string.
  6. If only the real part is zero, return just the imaginary part as a string followed by the letter i.

Step 5

Test what you have so far with the following code:

  //
  // === Test the toString() and Accessor functions ===
  //

  // create a complex number, set its values, and print it
  var cn1 = new ComplexNumber(); // construct a ComplexNumbr object
  cn1.real(2); // set the real part to 2
  cn1.imaginary(3); // set the imaginary part to 3
  pbs.say(cn1.toString()); // print it

  // create a second complex number, using 'function chianing' to do it all at once
  // NOTE: function chaining is only possible becuase both accessor functions return
  //       the special value this when they are used as setters.
  var cn2 = (new ComplexNumber()).real(2).imaginary(-4);
  pbs.say(cn2);

  // create some more complex number, but don't bother to save them, just print them
  pbs.say((new ComplexNumber()).real(-5.5).imaginary(1));
  pbs.say((new ComplexNumber()).real(7).imaginary(-1));
  pbs.say((new ComplexNumber()).real(2).imaginary(-6));
  pbs.say((new ComplexNumber()).real(-3));
  pbs.say((new ComplexNumber()).real(21));
  pbs.say((new ComplexNumber()).imaginary(-1));
  pbs.say((new ComplexNumber()).imaginary(1));
  pbs.say((new ComplexNumber()).imaginary(4.7));

Step 6

Add a function named parse to the ComplexNumber prototype to update the value stored in the calling complex number object. This function should allow the new value be specified in a number of different ways. The following should all work:

  1. Two numbers as arguments – first the real part, then the imaginary part.
  2. An array of two numbers as a single argument – the first element in the array being the real part, the second the imaginary part.
  3. A string of the form (a + bi) or (a - bi) where a is a positive or negative number, and b is a positive number.
  4. An object with the prototype ComplexNumber.

Step 7

Test the parse function you just created with the following code:

  //
  // === Test the Parse() function ===
  //

  var cn3 = new ComplexNumber(); // construct a ComplexNumbr object
  pbs.say(cn3.toString());

  // test the two-number form
  cn3.parse(2, 4);
  pbs.say(cn3.toString());

  // test the one array form
  cn3.parse([-3, 5.5]);
  pbs.say(cn3.toString());

  // test the one string form
  cn3.parse("(2 + 6i)");
  pbs.say(cn3.toString());
  cn3.parse("(2 - 6i)");
  pbs.say(cn3.toString());
  cn3.parse("(-2.76 + 6.2i)");
  pbs.say(cn3.toString());

  // test the one complex number object form
  var cn4 = (new ComplexNumber()).real(3).imaginary(4);
  cn3.parse(cn4);
  pbs.say(cn3.toString());

Step 8

Update your constructor so that it can accept the same arguments as the .parse() function. Do not copy and paste the code. Instead, update the constructor function to check if there are one or two arguments. If there are, call the parse function with the appropriate arguments.

Step 9

Test your updated constructor with the following code:

  //
  // === Test the Updated Constructor ===
  //

  // test the two-number form
  pbs.say( (new ComplexNumber(1, 2)).toString() );

  // test the one array form
  pbs.say( (new ComplexNumber([2, 3])).toString() );

  // test the one string form
  pbs.say( (new ComplexNumber("(2 - 6i)")).toString() );

  // test the one complex number object form
  var cn5 = new ComplexNumber(-2, -4);
  pbs.say( (new ComplexNumber(cn5)).toString() );

Step 10

Add a function named add to the ComplexNumber prototype which accepts one argument, a complex number object, and adds it to the object the function is called on. Note that you add two complex numbers by adding the real parts together, and adding the imaginary parts together.

Step 11

In a similar vain, add function named subtract to the ComplexNumber prototype. You subtract complex numbers by subtracting the real and imaginary parts.

Step 12

Add a function named multiplyBy to the ComplexNumber prototype. The rule for multiplying complex numbers is, appropriately enough, quite complex. It can be summed up by the following rule:

(a+bi) x (c+di) = (ac−bd) + (ad+bc)i

Step 13

Add a function named conjugateOf to the ComplexNumber prototype. This function should return a new ComplexNumber object with the sign of the imaginary part flipped. I.e. 2 + 3i becomes 2 - 3i and vice-versa.

Step 14

Test your arithmetic functions with the following code:

  //
  // === Test the Arithmentic Functions ===
  //

  // create a complex number to manipulate
  var myCN = new ComplexNumber(1, 2);
  pbs.say(myCN);

  // add 4 + 2i to our number
  myCN.add(new ComplexNumber(4, 2));
  pbs.say(myCN);

  // subtract 2 + i from our number
  myCN.subtract(new ComplexNumber(2, 1));
  pbs.say(myCN);

  // set the value to 3 + 2i
  myCN.parse(3, 2);

  // multiply by 1 + 7i
  myCN.multiplyBy(new ComplexNumber(1, 7));
  pbs.say(myCN.toString()); // should be -11 + 23i

  // get the conjugate
  myCN = myCN.conjugateOf();
  pbs.say(myCN.toString());

  // get the conjugate again
  myCN = myCN.conjugateOf();
  pbs.say(myCN.toString());

Join the Community

Find us in the PBS channel on the Podfeet Slack.

Podfeet Slack