Last active
July 2, 2016 14:00
-
-
Save spcheema/5c1f776737524fa8da20cd1b524dfdd4 to your computer and use it in GitHub Desktop.
Memory Puzzle solution
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
fs = require 'fs' | |
exports.countryIpCounter = (countryCode, cb) -> | |
return cb() unless countryCode | |
fs.readFile "#{__dirname}/../data/geo.txt", 'utf8', (err, data) -> | |
if err then return cb err | |
counter = 0 | |
data = data.toString() | |
### | |
* Converting string to array is more costly so | |
* I have changed algorithm to read string based on new line index | |
* | |
### | |
#data = data.toString().split '\n' | |
# read substring form input string and parse each line | |
loop | |
index = data.indexOf('\n') | |
line = data.substring(0, index) | |
# exit from loop if all lines from string are parsed | |
if line.length <= 0 | |
break | |
# split and parse line iff only it exists | |
if(line.length > 0) | |
# existing logic | |
line = line.split '\t' | |
# GEO_FIELD_MIN, GEO_FIELD_MAX, GEO_FIELD_COUNTRY | |
# line[0], line[1], line[3] | |
if line[3] == countryCode then counter += +line[1] - +line[0] | |
# remove parsed line from input | |
data = data.replace(data.substring(0, index+1), "") | |
cb null, counter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solution to memory puzzle
Replace
lib/index.coffee
file code with this