Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Created January 21, 2015 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amatiasq/c55531754bb480f7277f to your computer and use it in GitHub Desktop.
Save amatiasq/c55531754bb480f7277f to your computer and use it in GitHub Desktop.
// 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