Last active
August 28, 2019 16:44
-
-
Save benjamin-wss/0a8a55673f2a5f21766c to your computer and use it in GitHub Desktop.
String builder for JavaScript
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 StringBuilder(value) { | |
this.strings = new Array(); | |
this.append(value); | |
} | |
StringBuilder.prototype.append = function (value) { | |
if (value) { | |
this.strings.push(value); | |
} | |
} | |
StringBuilder.prototype.clear = function () { | |
this.strings.length = 0; | |
} | |
StringBuilder.prototype.toString = function () { | |
return this.strings.join(""); | |
} |
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
var sb = new StringBuilder(); | |
sb.append("This is"); | |
sb.append("much better looking"); | |
sb.append("than using +="); | |
// joins the string | |
var myString = sb.toString(); | |
// Cleans out the string buffer in the StringBuilder. | |
// This effectively makes it empty in case you did not | |
// know what cleaning out a buffer in this context | |
// meant. | |
sb.clear(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you please write more comments for the StringBuilder.js
I am trying to understand how it works.
Thanks