Created
January 21, 2015 11:01
-
-
Save amatiasq/c55531754bb480f7277f to your computer and use it in GitHub Desktop.
This file contains 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
// Calculates the space closest to the middle of the name | |
function splitName(name) { | |
var middle = name.length / 2; | |
var spaces = []; | |
var last = name.indexOf(' '); | |
while(last !== -1) { | |
spaces.push(last); | |
last = name.indexOf(' ', last + 1) | |
} | |
if (!spaces.length) { | |
return { | |
firstName: name, | |
lastName: '', | |
}; | |
} | |
var splitAt = spaces.reduce(function(current, position) { | |
var better = Math.abs(current - middle); | |
var distance = Math.abs(position - middle); | |
return distance < better ? position : current | |
}, name.length); | |
return { | |
firstName: name.substr(0, splitAt), | |
lastName: name.substr(splitAt + 1), | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment