Last active
April 25, 2017 21:36
-
-
Save owlishDeveloper/a932ea01e909aedea54a8b3f5db7c834 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
function wrap(string, value=23) { | |
if (value <= 0) | |
throw 'wrong number'; | |
if(string.length < value + 1) | |
return string; | |
var newArr = []; | |
for(var i=0; i<Math.floor(string.length/value)+1; i++) { | |
newArr.push(string.slice(i*value, i*value+value)); | |
} | |
//console.log(newArr); | |
return newArr.join('\n') | |
} | |
//console.log(wrap('Thisfeature has been removed from the Web standards. Though some browsersuuuuunuh')); | |
//console.log(wrap('d')); | |
console.log(wrap('Thisfeature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time', 0)); |
gracework
commented
Apr 25, 2017
- This is a good start at a naive implementation (splitting the string without concern for words).
- The hard-coded numerical constants (81, 79, 80) are all related to one another. They could be abstracted out into a single configurable variable, with some code adjustments around the comparisons / equalities they're testing.
Mutating an array while iterating over it is generally a bit error prone. I think it works in this case, but I'd prefer to make a new array. The String.prototype.slice
method would save us from having to split up the old string:
var newArr = [];
for (/* etc */) {
newArr.push(string.slice(i, i+80));
}
return newArr.join('\n')
// haven't tested!
I don't think this approach will extend very well to splitting on spaces. To get that far, I think we would need to implement a tokenizer (which would probably require third party libraries, and is too complicated to implement in 30 minutes).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment