JavaScript: StringBuilder


/ Published in: JavaScript
Save to your folder(s)

Emulates the StringBuilder() function found in .NET Languages


Copy this code and paste it in your HTML
  1. /*****************************************************************
  2.  * Stringbuilder Class - emulates the C#/VB.NET stringbuilder
  3.  * @constructor
  4.  *****************************************************************/
  5. function StringBuilder() {
  6. var strings = [];
  7.  
  8. this.append = function (string)
  9. {
  10. string = verify(string);
  11. if (string.length > 0) {
  12. strings[strings.length] = string;
  13. }
  14. };
  15.  
  16. this.appendLine = function (string)
  17. {
  18. string = verify(string);
  19. if (this.isEmpty())
  20. {
  21. if (string.length > 0) {
  22. strings[strings.length] = string;
  23. }
  24. else {
  25. return;
  26. }
  27. }
  28. else {
  29. strings[strings.length] = string.length > 0 ? "
  30. " + string : "
  31. ";
  32. }
  33. };
  34.  
  35. this.clear = function () { strings = []; };
  36.  
  37. this.isEmpty = function () { return strings.length == 0; };
  38.  
  39. this.toString = function () { return strings.join(""); };
  40.  
  41. var verify = function (string)
  42. {
  43. if (!defined(string)) {
  44. return "";
  45. }
  46. if (getType(string) != getType('string')) {
  47. return String(string);
  48. }
  49. return string;
  50. };
  51.  
  52. var defined = function (el)
  53. {
  54. return el != null && typeof(el) != "undefined";
  55. };
  56.  
  57. var getType = function (instance)
  58. {
  59. if (!defined(instance.constructor)) {
  60. throw new Error("Unexpected object type");
  61. }
  62. var type = String(instance.constructor).match(/function\s+(\w+)/);
  63.  
  64. return defined(type) ? type[1] : "undefined";
  65. };
  66. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.