I am trying to do something crazy, I have a JSON object of all sorts of rules for my website. I have a system set up where I can write pseudo code and then it turns it into actual code. I have this working perfectly for strings, however now I need to be able to pass functions, and replace the pseudo code inside of functions, then execute the functions.
I think I am on the right track, however when I turn a function to a string it only turns the output of the functions into a string.
Here's my JSON (part of it)
customValidation: {
//compare: "(<!this!> && <!PrimeTimeDiscount!> == 200) || (<!PrimeTimeDiscount!> == 100)",
compare: function(){
return new Validator()["date"]("<!this!>", 50);
},
overrideDefault: true
}
The commented out "compare" is how I use this system for regular strings.
And below is how I handle turning "<!this!>" and "<!*!>" into values from the JSON object. It is basically the same code twice, but the one below I have started modifying for when a function is detected.
if(typeof customValidationRule != "function")
{
var string = customValidationRule.match(/<!(.*?)!>/g);
var customValidationTerms = new Array();
var execCustomValidationRule = customValidationRule;
$.each(string, function(i, v){
var customValidationTerm = v.replace(/<!/g, "").replace(/!>/g, "");
customValidationTerms.push(customValidationTerm);
});
$.each(customValidationTerms, function(i, v){
var RegEx = new RegExp("<!"+v+"!>", "ig");
if(v == "this")
{
var newData = value ? value : "''";
}
else
{
var newData = FormData[parentKey][TermNames[v]] ? FormData[parentKey][TermNames[v]] : "''";
}
newData = dataType == "currency" ? cleanVar(cleanCurrency(newData)) : newData;
newData = newData ? newData : "''";
execCustomValidationRule = execCustomValidationRule.replace(RegEx, newData);
});
}
else
{
var customValidationRuleString = customValidationRule().toString();
var string = customValidationRuleString.match(/<!(.*?)!>/g);
var customValidationTerms = new Array();
var execCustomValidationRule = customValidationRuleString;
$.each(string, function(i, v){
var customValidationTerm = v.replace(/<!/g, "").replace(/!>/g, "");
customValidationTerms.push(customValidationTerm);
});
$.each(customValidationTerms, function(i, v){
var RegEx = new RegExp("<!"+v+"!>", "ig");
if(v == "this")
{
var newData = value ? value : "''";
}
else
{
var newData = FormData[parentKey][TermNames[v]] ? FormData[parentKey][TermNames[v]] : "''";
}
newData = dataType == "currency" ? cleanVar(cleanCurrency(newData)) : newData;
newData = newData ? newData : "''";
execCustomValidationRule = execCustomValidationRule.replace(RegEx, newData);
});
var backToFunction = eval('(' + execCustomValidationRule + ')');
//validation = customValidationRule();
}
validation = eval(execCustomValidationRule);
Related
i have a problem, I am trying to take the value of a field of the users table that I populated in the first while, but when I try to take the value in the second while of the second call, it returns 0, I cannot understand why, the values in the field are populated.
my code below:
var r = new sn_ws.RESTMessageV2('success_factors_api', 'GET');
var response = r.execute();
var reviver = function(key, value) {
if (typeof value === 'undefined') {
return null;
}
};
var responseBody = JSON.parse(response.getBody(), reviver());
var httpStatus = response.getStatusCode();
//gs.info(responseBody.d.results[0].nationalId);
var gr = new GlideRecord('sys_user');
gr.addEncodedQuery('u_codice_fiscaleISNOTEMPTY');
gr.query();
while (gr.next()) {
var fiscalCode = gr.getValue('u_codice_fiscale');
responseBody.d.results.forEach(function(obj) {
if (fiscalCode === obj.nationalId) {
gr.u_personal_id_external_successfactor = obj.personIdExternal;
gr.update();
}
});
}
var r2 = new sn_ws.RESTMessageV2('success_factors_api', 'GETEMPLOYMENT');
var response2 = r2.execute();
var reviver2 = function(key, value) {
if (typeof value === 'undefined') {
return null;
}
};
var responseBody2 = JSON.parse(response2.getBody(), reviver2());
var httpStatus2 = response2.getStatusCode();
gr.addEncodedQuery('u_personal_id_external_successfactorISNOTEMPTY');
while (gr.next()) {
var personalIdExternal = gr.getValue('u_personal_id_external_successfactor');
gs.info(personalIdExternal); //return me 0
responseBody2.d.results.forEach(function(obj) {
if (personalIdExternal === obj.personIdExternal) {
gr.u_user_id_successfactor = obj.userId;
gr.update();
}
});
}
Your second loop is missing a gr.query(). Also, you should never reuse a GlideRecord like that. Declare a new GlideRecord for the second loop.
I need to retrieve variables from an URL.
I use this found function:
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
The output is:
{"idPagamenti":["26","27"],"idCliente":["9"]}
But idCliente is always NOT an array, so i'd like to retrieve:
{"idPagamenti":["26","27"],"idCliente": 9 }
This is the fiddle example
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var stringa = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
$(document).ready(function(){
alert("testing");
console.log(me);
$(".a").html(JSON.stringify(me));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
</div>
Someone can help me to modify code?
I think your facing a real paradigm problem. Why idCliente wouldn't be an array but idPagamenti would be. You should have all array or none but not both. getParams() function can make this choice for you and you should probably change the way you are working with this.
Anyway, here is a getParams() function that replace any single-valued array to a value. Note that if you have only one idPagamenti in your URI, you will also have a single value for idPagamenti instead of an array.
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
Object.keys(obj).forEach(key => {
if (obj[key].length === 1) {
obj[key] = obj[key][0];
}
})
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
If you know that you will always get ids as parameters, you can also add a parseInt() for each parameter by replacing var value = spl[1]; with var value = parseInt(spl[1], 10);
i was tested to the IdentyfyTask.
But I could not get a response before the value addCallback.
i want to the pnu values.
But pnu vaule was alwayes undefined...
my code is follows.
function poiClick(){
agmap.addEvent("click", function(evt){
getPoi= krcgis.Function.PoiClick(agmap ,evt);
console.log("X === ",getPoi.x);
console.log("Y === ",getPoi.y);
console.log("PNU === ",getPoi.pnu);
});
}
PoiClick : function(map, evt) {
poiInfo = {};
poiInfo.x =evt.mapPoint.x;
poiInfo.y =evt.mapPoint.y;
var targetLayerId = 'LP_PA_CBND';
var url = map.Layers.getLayerInfo(targetLayerId).SVC_URL;
var map = map.getMap();
//파라미터 설정.
var idParams = new krcgis.core.tasks.IdentifyParameters();
idParams.geometry = evt.mapPoint;
idParams.mapExtent = map.extent;
idParams.returnGeometry = true;
idParams.tolerance = 0;
idParams.layerOption = krcgis.core.tasks.IdentifyParameters.LAYER_OPTION_ALL;
idParams.width = map.width;
idParams.height = map.height;
idTask = new krcgis.core.tasks.IdentyfyTask(url);
idTask
.execute(idParams)
.addCallback(function (response) {
if (response) {
poiInfo.pnu =response[0].value;
}
});
return poiInfo;
}
The results were as follows.
IdentifyTask returns a IdentifyResult object. so you code response[0].value will be undefined.
you should use something like response[0].feature.attributes.PNU
I'm running an A/B test to see if showing more items is better for conversion. But it seems that the code sometimes causes errors.. But I can't find any errors and don't know when they occur.
In my test I check whether the url param IC exists and if it doesn't exists I will add this.
This is my code:
function checkIfAlreadyPaginated()
{
var field = 'IC';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1)
return true;
else if(url.indexOf('&' + field + '=') != -1)
return true;
return false;
}
function insertParam(key, value) {
key = encodeURIComponent (key); value = encodeURIComponent (value);
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
return '?' + key + '=' + value;
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
return '?'+kvp.join('&');
}
}
var itemsPerPage = 48;
if(!checkIfAlreadyPaginated())
{
document.location.search = insertParam('IC', itemsPerPage);
}
Does someone spot possible issues? I'm running the test via VWO.com.
If there is a Javascript error you should see it in the browser console and share it with us.
In any case, I would do it by creating a JS Object first. I find it easier to work with.
In the following code I added the option to do the checking for multiple params of the querystring. If you only need to check the IC you can simplify it a bit. I tested it on a blank test.html.
<script type="text/javascript">
// get the current params of the querystring
var querystringItems = document.location.search.substr(1).split('&');
// create an object
var querystringObject = {};
for(i=0;i<querystringItems.length;++i) {
param = querystringItems[i].split('=');
querystringObject[param[0]] = param[1];
}
// Define the keys to be searched for and their default value when they are not present
var requiredKeys = {"IC":48, "test": "me"};
// Do the checking on the querystringObject for each requiredKeys
var doreload = false;
for (var key in requiredKeys) {
if (typeof querystringObject[key] == 'undefined') {
doreload = true;
// Create the missing parameter and assign the default value
querystringObject[key] = requiredKeys[key];
}
}
// If any of the requiredKeys was missing ...
if (doreload) {
// rebuild the querystring
var querystring = '?';
for (var key in querystringObject) {
querystring+=key+'='+querystringObject[key]+'&';
}
querystring=querystring.substr(0,querystring.length-1);
// reload page
document.location.search = querystring;
}
// assign the values to javascript variables (assuming you had it like this because you needed it)
var itemsPerPage = querystringObject.IC;
</script>
Here is an example to check this:
//get URL params into string:
paramStr = window.location.substring(window.location.indexOf('?'), window.location.length;
//turn string into array
paramArray = paramStr.split('&');
//prepare final array of params
params = {};
//prepare the index of IC parameter
icLoc = -1; //this is negative 1 so that you know if it was found or not
//for each item in array
for(var i in paramArray){
//push its name and value to the final array
params.push(paramArray[i].split('='));
//if the parameter name is IC, output its location in array
if(params[i][0] === 'IC'){
icLoc = i;
}
}
If IC is not found, icLoc will be -1.
If it is found, the value of IC in the URL parameters is params[icLoc][1]
Example result for query string ?foo=bar&code=cool&IC=HelloWorld:
params = {'foo': 'bar', 'code': 'cool', 'IC': 'HelloWorld'}
icLoc = 2
Example for query string ?foo=bar&code=cool:
params = {'foo': 'bar', 'code': 'cool'}
icLoc = -1
Here id is the param I'm using for a test. Pass the argument which you want to check whether it exists or not.
function queryParamExistUrl(param = '') {
if (new URLSearchParams(window.location.search).get(param) != null)
return true
return false
}
console.log(queryParamExistUrl('id'))
How to use JSON.parse reviver method to edit a certain value.
I just want to edit every key which is declared as lastname and than return the new value.
var myObj = new Object();
myObj.firstname = "mike";
myObj.lastname = "smith";
var jsonString = JSON.stringify(myObj);
var jsonObj = JSON.parse(jsonString, dataReviver);
function dataReviver(key, value)
{
if(key == 'lastname')
{
var newLastname = "test";
return newLastname;
}
}
After checking for the special case(s), you simply need to pass back unmodified values by default:
var myObj = new Object();
myObj.firstname = "mike";
myObj.lastname = "smith";
var jsonString = JSON.stringify(myObj);
var jsonObj = JSON.parse(jsonString, dataReviver);
function dataReviver(key, value)
{
if(key == 'lastname')
{
var newLastname = "test";
return newLastname;
}
return value; // < here is where un-modified key/value pass though
}
JSON.stringify(jsonObj )// "{"firstname":"mike","lastname":"test"}"