Chapter 3 Exercise Set 1

Set of names

The solution for the cat problem talks about a “set” of names. A set is a collection of values in which no value may occur more than once. If names are strings, can you think of a way to use an object to represent a set of names?

Show how a name can be added to this set, how one can be removed, and how you can check whether a name occurs in it.

range(n)

Write a function range that takes one argument, a positive number, and returns an array containing all numbers from 0 up to and including the given number.

An empty array can be created by simply typing []. Also remember that adding properties to an object, and thus also to an array, can be done by assigning them a value with the = operator. The length property is automatically updated when elements are added.

split and join

split and join are not precisely each other’s inverse. string.split(x).join(x) always produces the original value, but array.join(x).split(x) does not. Can you give an example of an array where .join(" ").split(" ") produces a different value?

extractDate(s)

"died 04/27/2006: Black Leclère"

The date part is always in the exact same place of a paragraph. How convenient. Write a function extractDate that takes such a paragraph as its argument, extracts the date, and returns it as a date object.

between(string, start, end)

The thing that extractMother does can be expressed in a more general way. Write a function between that takes three arguments, all of which are strings. It will return the part of the first argument that occurs between the patterns given by the second and the third arguments.

So between("born 11/15/2003 (mother Spot): White Fang", "(mother ", ")") gives "Spot".

between("bu ] boo [ bah ] gzz", "[ ", " ]") returns "bah".

To make that second test work, it can be useful to know that indexOf can be given a second, optional parameter that specifies at which point it should start searching.

formatDate

The formatDate function used by catInfo does not add a zero before the month and the day part when these are only one digit long. Write a new version that does this.

oldestCat

Write a function oldestCat which, given an object containing cats as its argument, returns the name of the oldest living cat.

range(start, [stop])

Extend the range function from range(n) to take a second, optional argument. If only one argument is given, it behaves as earlier and produces a range from 0 to the given number. If two arguments are given, the first indicates the start of the range, the second the end.

sum

You may remember this line of code from the introduction:

print(sum(range(1, 10)));

We have range now. All we need to make this line work is a sum function. This function takes an array of numbers, and returns their sum. Write it, it should be easy.