documentcloud/underscore — pull request #1112 by lightblade (2013-05-11 19:56:09+00:00)
Title: _.transform Applies a function to perform transformation on the object

The goal is to supply a function to work with the object itself. Most underscore functions work with collections and treats objects as only associative array. #1068 may be related, but that pull request still work the object as an associative array.

The main use case is during chaining that you'll want to apply a certain function to the wrapped object.

```javascript
// The goal of this snippet is to select cells in table,
// do filter on them, then wrap it back as a jQuery object
_.chain($('td')) // One of the great thing about underscore is
// that it work with any array-like object
.groupBy('cellIndex')
.sortBy(function(__, key) {
return Number(key)
})
.first()
.transform($)
.value()
.css('background-color', 'red')
```

Alternative solution without `_.transform` may be ugly because it disrupts the structure flow.

```javascript
$(_.chain($('td'))
.groupBy('cellIndex')
.sortBy(function(__, key) {
return Number(key)
})
.first())
.value()
.css('background-color', 'red')
```

Naming-wise, it may be more appropriate to call it `apply`. But since the `_` object is itself a function and we don't want to override `Function.prototype.apply`, I came up with the `transform` alternative.

Alternatively, the functionality may be merged with either `_.chain().value(function)` or `_.tap(function)` by making the chain returns tap's function return value if it does return something. Something like this

```javascript
_.tap = function(obj, inter) {
return inter(obj) || obj
}
```