tyebillion tyebillion - 3 months ago 11
Javascript Question

Is it possible to factorise these functions each containing similar code?

I have two Javascript functions that both use jquery-confirm (https://craftpip.github.io/jquery-confirm/) and contain very similar code:

function cnf(cntn, fn) {
$.confirm({
title: "",
content: cntn,
confirmButton: "Yes",
cancelButton: "No",
confirm: function() { fn(); },
cancel: function() { }
});
}
function cnfprm(cntn, fn, prm) {
$.confirm({
title: "",
content: cntn,
confirmButton: "Yes",
cancelButton: "No",
confirm: function() { fn(prm); },
cancel: function() { }
});
}


I was wondering if it is possible to factorise this code by creating another function that encapsulates the similarities of both of these calls, so the resulting code is something like:

function cnf(cntn, fn) {
subfn(cntn, confirm: function() { fn(); });
}
function cnfprm(cntn, fn, prm) {
subfn(cntn, confirm: function() { fn(prm); });
}


...or if there is another way to factorise the code?

Answer

I think you can use this:

function cnf(cntn, fn){
  cnfprm(cntn, fn);
}

function cnfprm(cntn, fn, prm) {
  $.confirm({
    title: "",
    content: cntn,
    confirmButton: "Yes",
    cancelButton: "No",
    confirm: function() {
      if(prm !== undefined){ fn(prm); }else{ fn(); }
    },
    cancel: function() { }
  });
}