Skip to content

Commit

Permalink
Add Twitter::Utils#pmap_with_index
Browse files Browse the repository at this point in the history
  • Loading branch information
sferik committed Mar 1, 2014
1 parent 302a9d8 commit dfe7b1d
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Rakefile
Expand Up @@ -31,7 +31,7 @@ end

require 'yardstick/rake/verify'
Yardstick::Rake::Verify.new do |verify|
verify.threshold = 59.7
verify.threshold = 59.6
end

task :default => [:spec, :rubocop, :verify_measurements]
2 changes: 1 addition & 1 deletion examples/AllTweets.md
Expand Up @@ -16,7 +16,7 @@ an empty response.

```ruby
def collect_with_max_id(collection=[], max_id=nil, &block)
response = yield max_id
response = yield(max_id)
collection += response
response.empty? ? collection.flatten : collect_with_max_id(collection, response.last.id - 1, &block)
end
Expand Down
2 changes: 1 addition & 1 deletion lib/twitter/client.rb
Expand Up @@ -21,7 +21,7 @@ def initialize(options = {})
options.each do |key, value|
send(:"#{key}=", value)
end
yield self if block_given?
yield(self) if block_given?
validate_credential_type!
end

Expand Down
2 changes: 1 addition & 1 deletion lib/twitter/enumerable.rb
Expand Up @@ -6,7 +6,7 @@ module Enumerable
def each(start = 0, &block)
return to_enum(:each, start) unless block_given?
Array(@collection[start..-1]).each do |element|
yield element
yield(element)
end
unless last?
start = [@collection.size, start].max
Expand Down
17 changes: 14 additions & 3 deletions lib/twitter/utils.rb
Expand Up @@ -22,13 +22,24 @@ def deprecate_alias(new_name, old_name)
# @return [Array, Enumerator]
def pmap(enumerable)
return to_enum(:pmap, enumerable) unless block_given?
pmap_with_index(enumerable).sort_by { |_, index| index }.collect { |object, _| yield(object) }
end
module_function :pmap

# Calls block with two arguments, the item and its index, for each item in enumerable. Given arguments are passed through to pmap.
# If no block is given, an enumerator is returned instead.
#
# @param enumerable [Enumerable]
# @return [Array, Enumerator]
def pmap_with_index(enumerable)
return to_enum(:pmap_with_index, enumerable) unless block_given?
# Don't bother spawning a new thread if there's only one item
if enumerable.count == 1
enumerable.collect { |object| yield object }
enumerable.collect { |object| yield(object, 0) }
else
enumerable.collect { |object| Thread.new { yield object } }.collect(&:value)
enumerable.each_with_index.collect { |object, index| Thread.new { yield(object, index) } }.collect(&:value)
end
end
module_function :pmap
module_function :pmap_with_index
end
end

0 comments on commit dfe7b1d

Please sign in to comment.