if (typeof String.prototype.supplant !== 'function') {
String.prototype.supplant = function (o) {
return this.replace(/{{([^{}]*)}}/g, function (a, b) {
var r = o[b];
return typeof r === 'string' ? r : a;
});
};
}
var obj = {
a: "text",
b: "text 2",
c: "text 3"
}
var stringA = "http://{{a}}.something.com/",
stringB = "http://something.{{b}}.com/",
stringC = "http://something.com/{{c}}";
alert(stringA.supplant(obj));
function escapeHTML(text) {
var replacements = {
"<": "<",
">": ">",
"&": "&",
"\"": """
};
return text.replace(/[<>&"]/g, function(character) {
return replacements[character];
});
}
var list = [1,2,3,4,5,6,7,8,9];
list = list.sort(function() {
return Math.random() - 0.5;
});
console.log(list);
Sometimes you need to do things in order. Do one thing, wait for it to finish, maybe asynchronous, and the continue with the next one. This in programming is called a tail implementation. Here is a very basic tail in javascript.
var data = [16, 11, 9, 7, 26, 25],
len = data.length,
tail = [],
start = null,
i;
// simulate lots of data
for (i = 0; i < len; i++) {
go({pos:i, val:data[i]});
}
/**
* Entry point - incomming data!
*/
function go(obj) {
// add data to tail array
tail.push(obj);
// start first run, on first data entry
if (!start) {
run(tail.shift(), finish);
// start the loop
start = true;
}
}
/**
* Run command from tail array
*/
function run(obj, cb) {
var delay = getRandomInt(1000, 5000);
// simulates job, with different time execution
setTimeout(function() {
console.log("CMD: " + obj.pos + ":" + obj.val);
cb({isok:"OK", delay:delay});
}, delay);
}
/**
* Callback from run(). Hare we contionue the
* execution if tail array contains other commands.
*/
function finish(res) {
console.log("RES: isok:" + res.isok + " delay:" + res.delay);
console.log("INF: tail length:" + tail.length);
console.log("==========");
// if no data in array, stop execution
if (tail.length === 0) {
// stop the loop
start = null;
return;
// if still data continue execution with next tail element
} else {
run(tail.shift(), finish);
}
}
/**
* Randomly generated delay
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}