Last active
October 28, 2016 12:56
-
-
Save ghiculescu/e6ddeb466ec42e8e074a4d67ac2dbc00 to your computer and use it in GitHub Desktop.
can i solve https://github.com/TandaHQ/work-samples/tree/master/pings%20(backend) in less than an hour
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# i wish i did this in JS | |
require 'sinatra' | |
require 'fileutils' | |
require 'json' | |
require 'date' | |
require 'time' | |
require 'byebug' | |
get "/devices" do | |
content_type :json | |
Dir.glob("files/*").to_json | |
end | |
get "/:device_id/:date" do | |
content_type :json | |
files = if params[:device_id] == 'all' | |
Dir.glob("files/*").map {|f| | |
data = File.read(f).each_line.to_a.map(&:strip).find_all {|t| | |
start = Date.parse(params[:date]).to_time | |
finish = start + 86400 | |
t = Time.at(t.to_i) | |
t >= start && t <= finish | |
} | |
[f, data] | |
}.to_h | |
else | |
File.read("files/#{params[:device_id]}").each_line.to_a.map(&:strip).find_all {|t| | |
start = Date.parse(params[:date]).to_time | |
finish = start + 86400 | |
t = Time.at(t.to_i) | |
t >= start && t <= finish | |
} | |
end.to_json | |
end | |
get "/:device_id/:from/:to" do | |
content_type :json | |
files = if params[:device_id] == 'all' | |
Dir.glob("files/*").map {|f| | |
data = File.read(f).each_line.to_a.map.find_all {|t| | |
start = Date.parse(params[:from]).to_time rescue Time.at(params[:from].to_i) | |
finish = Date.parse(params[:to]).to_time rescue Time.at(params[:to].to_i) | |
t = Time.at(t.to_i) | |
t >= start && t < finish | |
} | |
[f, data] | |
}.to_h | |
elsif File.exist?(File.read("files/#{params[:device_id]}")) | |
File.read("files/#{params[:device_id]}").each_line.to_a.map(&:strip).find_all {|t| | |
start = Date.parse(params[:from]).to_time rescue Time.at(params[:from].to_i) | |
finish = Date.parse(params[:to]).to_time rescue Time.at(params[:to].to_i) | |
t = Time.at(t.to_i) | |
t >= start && t < finish | |
} | |
else | |
[] | |
end.to_json | |
end | |
post "/:device_id/:timestamp" do | |
FileUtils.mkdir_p("files") | |
File.open("files/#{params[:device_id]}", 'a') { |f| f.puts params[:timestamp]} | |
status 200 | |
end | |
post "/clear_data" do | |
FileUtils.rm_rf("files") | |
status 200 | |
end |
That was fun! We should do live code challenges more often.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow. So much better than JavaScript!