Smooth CoffeeScript

Page 68

Data Structures

Strings also have a method called slice. It copies out a piece of the string, starting from the character at the position given by the first argument, and ending before (not including) the character at the position given by the second one. It is the same as using a range as an index. This allows the check to be written in a shorter way. show paragraph.slice(0, 4) == 'born' show paragraph[0...4] == 'born'

Exercise 13 Write a function called startsWith that takes two arguments, both strings. It returns true when the first argument starts with the characters in the second argument, and false otherwise. What happens when charAt, slice or a range are used to take a piece of a string that does not exist? Will the startsWith still work when the pattern is longer than the string it is matched against? show 'Pip'.charAt 250 show 'Nop'.slice 1, 10 show 'Pin'[1...10] charAt will return '' when there is no character at the given position, and slice or the range will simply leave out the part of the new string that

does not exist. So yes, startsWith should work. When startsWith('Idiots', 'Most honoured colleagues') is called, the call to slice will, because string does not have enough characters, always return a string that is shorter than pattern. Because of that, the comparison with == will return false, which is correct. It helps to always take a moment to consider abnormal (but valid) inputs for a program. These are usually called corner cases, and it is very common for programs that work perfectly on all the ‘normal’ inputs to screw up on corner cases.

◦•◦ The only part of the cat-problem that is still unsolved is the extraction of names from a paragraph. The algorithm was this:

67


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.