Skip to content
Myr

Added callback() helper for shorthand function expressions

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by visionmedia · committed by visionmedia · parent 04dd980 · Browse files · 2 files+22 added−5 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+22 added−5 removed

  • tests:+5 added−0 removed
  • other:+17 added−5 removed

2 files+22 added−5 removed

modified:lib/express/collection.js+17 added-5 removed
12// Express - Collection - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34// TODO: isArray()5// TODO: v8 native merge?6// TODO: getters7// TODO: benchmarks84/**5 * Throw $break in order to stop iteration.6 */78$break = '__break__'910/**11 * Normalize callback _fn_. When a string is12 * passed convert the shorthand expr to a function.13 *14 * @param {string, function} fn15 * @return {function}16 * @api private17 */1819function callback(fn) {20 return fn instanceof Function ? fn :21 fn.length < 4 ?22 Function('a, b, c', 'return a ' + fn + ' b') :23 Function('a, b, c', 'return ' + fn)24}2526// --- Collection2728Collection = Class({29
66 unmodified lines
96 * @api public97 */98 99 reduce: function(memo, fn) {100 fn = callback(fn)101 if (this.arr.reduce)102 return this.arr.reduce(fn, memo)103 this.each(function(val, key){104 memo = fn(memo, val, key)
370 unmodified lines
modified:spec/spec.collection.js+5 added
61 unmodified lines
62 it 'should iterate with memo object'63 var sum = $([1,2,3]).reduce(0, function(sum, n){ return sum + n })64 sum.should.eql 665 end66 67 it 'should allow expression shorthand'68 $([1,2,3]).reduce(0, '+').should.eql 669 $([1,2,3]).reduce(0, 'a + b').should.eql 670 end71 end72 73 describe '#map()'74 it 'should iterate collecting results into a new collection'
297 unmodified lines