Skip to content

Instantly share code, notes, and snippets.

@jesslilly
Created February 5, 2014 16:16
Show Gist options
  • Save jesslilly/8827229 to your computer and use it in GitHub Desktop.
Save jesslilly/8827229 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
/*=========================================================
Break up a string of words with no spaces into a string of words with appropriate spaces.
=========================================================*/
var dictionary = {
'the' : 0,
'a' : 0,
'may' : 0,
'be' : 0,
'maybe' : 0
};
/* ===============================================================
@input: String with no spaces…
@return: String with appropriate spaces added!
Assumption is that all words in the input are dictionary words.
=============================================================== */
var breakUp = function(input) {
if (input === undefined || input === null || input === "") {
return "";
}
var answer = [];
var startPos = 0;
for ( var idx = 1; idx <= input.length; ++idx ) {
var word = input.substring(startPos, idx);
if (word in dictionary) {
answer.push(word);
startPos = idx;
}
}
return answer.join(" ");
};
/* ===============================================================
* Unit tests. Normally I would do this in jasmine.
=============================================================== */
console.log(breakUp("athemaybe") === "a the may be");
console.log(breakUp("a") === "a");
console.log(breakUp("") === "");
console.log(breakUp("maybe") === "may be");
console.log(breakUp("maythemaybebe") === "may the may be be");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment