Ode to expressiveness

Reading /r/dailyprogrammer I found a typical programming problem, a change calculator: write a function that given certain amount of money, returns the minimal number of coins to change the money. The arbitrary values for those coins are 1, 5, 10 and 20 (this problem can be also be rendered in cents, but is pretty much the same). However, what most surprised me, it was compare the solutions provided by the users in JavaScript and Cobol:

 

Wow. 108 lines of code. Now let’s see a possible solution in JavaScript:

What I really love about JavaScript is its expresiveness. Of course you could also write a similar program with Python or LISP or whatever, but let’s just take JavaScript as example. The things I like are:

  • Literal notation. Rather than creating an agreggator object or a collection, we can declare our array of coins in-place and call immeditaly the function .map upon it. 
  • Using literal expressions let us easily adapt or expand our solution. If the problem changes and now we need to return coins of 3, 7 and 15 value, we can do it right away!
  • Returning function types. Since functions in JavaScript are first class citizens, we can return them inside other functions. This let us specify clearly that our main function, coins(), is actually returning the result of certain algorithm or function
  • Closures. A closure is an internal function or variable having access to the scope of an external function. We see a clear example of that when in our inner return type we build a two dimensional array, using the second position to re-assign the value of amount
  • …ok, perhaps building a two dimensional array, making an assignment in the second position and returning only the first element [0] is kinda jerkoff, but closures are nevertheless quite powerful.
  • Add properties to objects on the fly. My own solution to this problem looks kinda like this (pretty much the same but more readable I believe)

  • We can see the assignment of res[coin] as inserting a new key into an array, but the possibilities are much more powerful than that, since res is an object I could easily added a function to it or do basically whatever I want. Awesome!

You can play around with it here