JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/qunit/1.18.0/qunit.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/qunit/qunit-1.23.1.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.21.0/ramda.min.js"></script>
<div id="qunit">
</div>
<div id="qunit-fixture"></div>
JavaScript
//Imperative, stateful for
// One could build the string on the fly and avoid the array, but I would discourage that (unless you have **extreme** performance requirements)
var demoImperative = function(str, chunkLength, delimiter = "\n", maxLines = 3) {
var chunks = [];
for (var index = 0; index < str.length && chunks.length < maxLines; index += chunkLength) {
// NOTE: substr != substring. See http://stackoverflow.com/questions/3745515/what-is-the-difference-between-substr-and-substring
chunks.push(str.substr(index, chunkLength));
}
return chunks.join(delimiter);
}
// Using js RegExp, one can split the string with native functions
// This is probably the best if one is unwilling to introduce other libraries, but the RegExp is a bit opaque
var demoRegExp = function(str, chunkLength, delimiter = "\n", maxLines = 3) {
// This RegExp is taken from http://stackoverflow.com/questions/12686746/split-a-string-at-every-nth-position-with-javascript
var regExp = new RegExp('.{1,'+chunkLength+'}', 'g');
return str.match(regExp).slice(0,maxLines).join(delimiter);
}
// Just for fun, here's how I would tackle this in Ramda.js
var demoRamda = function(str, chunkLength, delimiter = "\n", maxLines = 3) {
return R.pipe(
R.splitEvery(chunkLength),
R.take(maxLines),
R.join(delimiter)
)(str);
}
//##############################################################################
// Tests
//##############################################################################
var doTests = function(testFunction) {
QUnit.test("one word", function(assert) {
assert.equal(testFunction("mittens", 81), "mittens");
});
QUnit.test("two words", function(assert) {
assert.equal(testFunction("teal mittens", 81), "teal mittens");
});
QUnit.test("two words/split", function(assert) {
assert.equal(testFunction("teal mittens", 8), "teal mit\ntens");
});
QUnit.test("three words/split", function(assert) {
assert.equal(testFunction("teal...