Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1699 How can I create a fixed length String Buffer that I can append text to?

You are here: irt.org | FAQ | JavaScript | Text | Q1699 [ previous next ]

Try:

<html>

<head>

<script language="JavaScript"><!--
function append(value) {
  if (this.value.index + value.length > this.size) {
    value = (this.value.substring(0,this.index) + value).substring(0, this.value.size);
    this.size = this.index = value.length;
  }
  else {
    value = this.value.substring(0,this.index) + value;
    this.index = value.length;
  }
  this.value = value + this.value.substring(value.length, this.value.length);
}

function getValue() {
  return this.value;
}

function duplicateString(size, chr) {
  var text = '';
  for (var i=0; i<size; i++)
    text += chr;
  return text;
}

function StringBuffer(size, chr) {
  this.value = new String(duplicateString(size, chr));
  this.size = size;
  this.index = 0;
  this.append = append;
  this.toString = getValue;
}
//--></script>

</head>

<body>

<script language="JavaScript"><!--
var text = new StringBuffer(100,'-');

for (var i=0; i<100; i++) {
  text.append('a');
  document.write(text + '<br>');
}
//--></script>

</body>

</html>

©2018 Martin Webb