Supplanting Data with Equations


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



Copy this code and paste it in your HTML
  1. String.prototype.supplant = function (o) {
  2. return this.replace(/{([^{}]*)}/g,
  3. function (a, b) {
  4.  
  5. //Evaluators
  6. var ev = {
  7. _Object: /([^\[\]]*)\[([^\[\]]*)\]/g,
  8. _Equation: /([^\=\!\?]*)([\=\!\?]*)([^\?\:]*)([\?\:]*)([^\?\:]*)([\?\:]*)([^\?\:]*)/g
  9. };
  10.  
  11. //Test if it's an equation - A==B?this:that
  12. var _1 = b.indexOf('?');
  13.  
  14. if (_1 !== -1) {
  15.  
  16. var ci = null;
  17. b.replace(ev._Equation, function (x, y, z, xx, yy, zz, xxx, yyy, zzz) {
  18. //Seems to fire twice, yet to work that out
  19. if (x == "") return;
  20.  
  21. //A==B?this:that would create
  22. //equation = {
  23. // l: "A", left
  24. // r: "B", right
  25. // s: "this", success
  26. // f: "that" fail
  27. //}
  28. var equation = {
  29. l: y.replace(ev._Object, function (x, y, z) {
  30. return o[y][z]
  31. }) || y,
  32. r: (z != '?') ? xx : null,
  33. s: (z != '?') ? zz : xx,
  34. f: (z != '?') ? yyy : zz
  35. },
  36. evald = null;
  37.  
  38. if (z != '?') {
  39. evald = eval(equation.l + z + equation.r);
  40. } else {
  41. evald = o[equation.l];
  42. }
  43.  
  44. if (evald == true)
  45. ci = equation.s;
  46. if (evald == false)
  47. ci = equation.f;
  48.  
  49. });
  50. return ci;
  51.  
  52. } else {
  53. var r = o[b];
  54. return typeof r === 'string' ? r : a;
  55. }
  56.  
  57. }
  58. );
  59. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.