Interpolate unit testing

by Arnaud Buchholz

CSS

.ok {
  color: green;
}

.ko {
  color: red;
}

JavaScript

function _interpolate (any, mValues) {
		var sType = typeof any;
		if (sType === "string") {
			return any.replace(/\${([^}]+)}/g, function (match, key) {
				return mValues[key];
			});
		}
		if (any && sType === "object") {
			Object.keys(any).forEach(function (sPropertyName) {
				any[sPropertyName] = _interpolate(any[sPropertyName], mValues);
			});
		}
		return any;
	}
  
  function assert (condition, message) {
  	var line = document.createElement("div");
    line.appendChild(document.createTextNode(message));
    line.className = condition ? "ok" : "ko";
    document.body.appendChild(line);
  }
    
  var test1 = "This is a ${TEST}";
  assert(_interpolate(test1, {
  	TEST: "test"
  }) === "This is a test", "test1");
  
  var test2 = {
  	string1: "Hello World!",
    string2: "${HELLO} ${WORLD}!",
    number1: 3,
    boolean1: true,
    sub: {
    	string3: "{HELLO} {WORLD}",
      string4: "${HELO}",
      boolean2: false
    },
    "null": null
  };
  var interpolatedTest2 = _interpolate(test2, {
  	"HELLO": "Hello",
    "WORLD": "World",
    "ANY": "test"
  });
  assert(interpolatedTest2 === test2, "Same object modified");
  assert(interpolatedTest2.string2 === "Hello World!", "string2 interpolated to " + interpolatedTest2.string2);
  assert(interpolatedTest2.number1 === 3, "number1 is not modified");
  assert(interpolatedTest2.boolean1, "boolean1 is not modified");
  assert(interpolatedTest2.sub.string3 === "{HELLO} {WORLD}", "interpolatedTest2.sub.string3 is not modified");
    assert(interpolatedTest2.sub.string4 === "undefined", "interpolatedTest2.sub.string4 interpolated to " + interpolatedTest2.sub.string4);