Smooth CoffeeScript

Page 169

Modularity

There are functions which require a lot of arguments. Sometimes this means they are just badly designed, and can easily be remedied by splitting them into a few more modest functions. But in other cases, there is no way around it. Typically, some of these arguments have a sensible ‘default’ value. We could, for example, write yet another extended version of range. range = (start, end, stepSize , length) -> if stepSize == undefined stepSize = 1 if end == undefined end = start + stepSize * (length - 1) result = [] while start <= end result.push start start += stepSize result show range 0, undefined , 4, 5

It can get hard to remember which argument goes where, not to mention the annoyance of having to pass undefined as a second argument when a length argument is used. We can make passing arguments to this unfriendly function more comprehensive by wrapping them in an object. defaultTo = (object, values) -> for name, value of values if not object.hasOwnProperty name object[name] = value range = (args) -> defaultTo args, {start: 0, stepSize: 1} if args.end == undefined args.end = args.start + args.stepSize * (args.length - 1) result = []; while args.start <= args.end result.push args.start args.start += args.stepSize result show range {stepSize: 4, length: 5}

The defaultTo function is useful for adding default values to an object. It

168


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