alter.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // alter.js
  2. // MIT licensed, see LICENSE file
  3. // Copyright (c) 2013 Olov Lassus <olov.lassus@gmail.com>
  4. var assert = require("assert");
  5. var stableSort = require("stable");
  6. // fragments is a list of {start: index, end: index, str: string to replace with}
  7. function alter(str, fragments) {
  8. "use strict";
  9. var isArray = Array.isArray || function(v) {
  10. return Object.prototype.toString.call(v) === "[object Array]";
  11. };;
  12. assert(typeof str === "string");
  13. assert(isArray(fragments));
  14. // stableSort isn't in-place so no need to copy array first
  15. var sortedFragments = stableSort(fragments, function(a, b) {
  16. return a.start - b.start;
  17. });
  18. var outs = [];
  19. var pos = 0;
  20. for (var i = 0; i < sortedFragments.length; i++) {
  21. var frag = sortedFragments[i];
  22. assert(pos <= frag.start);
  23. assert(frag.start <= frag.end);
  24. outs.push(str.slice(pos, frag.start));
  25. outs.push(frag.str);
  26. pos = frag.end;
  27. }
  28. if (pos < str.length) {
  29. outs.push(str.slice(pos));
  30. }
  31. return outs.join("");
  32. }
  33. if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
  34. module.exports = alter;
  35. }