0

我有一个这样的数组:

tweets = [
  {
    :user_id => 234567,
    :username => "A",
    :created_at => "2012-10-12 10:20:30"
  },
  {
    :user_id => 234568,
    :username => "B",
    :created_at => "2012-10-12 10:20:34"
  },
  {
    :user_id => 234569,
    :username => "C",
    :created_at => "2012-10-12 10:20:35"
  },
  {
    :user_id => 234570,
    :username => "D",
    :created_at => "2012-10-12 10:20:40"
  }
]

和另一个数组,像这样:

followers = [
  {
    :user_id => 234567,
    :follower_ids => [234568, 56654]
  },
  {
    :user_id => 234568,
    :follower_ids => [234569, 454445]
  },
  {
    :user_id => 234569,
    :follower_ids => [234570, 56333]
  },
  {
    :user_id => 234570,
    :follower_ids => [45566, 61145]
  }
]

我想将它嵌套到一个深层结构中,其中一个被制成另一个的孩子。对于制作孩子,要满足的条件是:

任何其他比其他推文更大的推文,并且如果追随者数组中的推文被认为是孩子,则created_at其包含在 follower_ids 列表中user_id

给定数据的预期输出如下:

arranged_tweets = [
  {
    :user_id => 234567,
    :username => "A",
    :created_at => "2012-10-12 10:20:30",
    :children => [
      {
        :user_id => 234568,
        :username => "B",
        :created_at => "2012-10-12 10:20:34",
        :children => [
          {
            :user_id => 234569,
            :username => "C",
            :created_at => "2012-10-12 10:20:35",
            :children => [
              {
                :user_id => 234570,
                :username => "D",
                :created_at => "2012-10-12 10:20:40"
              }
            ]
          }
        ]
      }
    ]
  }
]
4

1 回答 1

1

未经测试,但应该给你的想法:

arranged_tweets = tweets.collect do |tweet|
  arranged_tweet(tweet, tweets - [tweet])          
end

def arranged_tweet(tweet, other_tweets)
  { :user_id => tweet[:user_id], ...
    :children => children(tweet, other_tweets) }
end 

def children(tweet, other_tweets)
  other_tweets.find_all { |other| is_child?(other, tweet) }.collect do |other|
    arranged_tweet(other, other_tweets - [other]) 
  end              
end

def is_child?(tweet, parent_tweet)
   parent_tweet[:created_at] > tweet[:created_at] && 
     is_follower?(tweet[:user_id], parent_tweet[:user_id])                                  
end

def is_follower?(user_id, other_user_id)
  followers[other_user_id][:follower_ids].include?(user_id)
end
于 2013-06-13T09:32:41.187 回答