I am proxying the function console.log to add some information to my logs and I am as well checking whether the information being logged is an object. I do this to avoid getting a log entry of the sort
2016-12-17 (22:12:51) > [object Object]
Code works fine when passing arguments that are not objects. For example, the command
console.log("hello","world");
prints
2016-12-17 (22:23:53) > hello
2016-12-17 (22:23:53) > world
But if I pass an object as well, the code will fail to insert a new line after the object. For example, the command
console.log("hello",{world:true,hello:{amount:1,text:"hello"}},"world");
prints
2016-12-17 (22:27:32) > hello
2016-12-17 (22:27:32) > { world: true, hello: { amount: 1, text: hello } } 2016-12-17 (22:27:33) > world
(note the missing line break after displaying the object).
Code
JQuery 3.1.1
main.js:
(function (proxied) {
function displayArg(argument){
var result= "";
if(typeof argument == "object") {
result += "{ ";
for (i in argument) {
result += i + ": ";
result += (displayArg(argument[i]));
result += ", "
}
result = result.substring(0,result.length - 2);
result += " }";
return result;
} else {
return argument;
}
}
console.log = function () {
var result = [];
for (i in arguments) {
var d = new Date();
result[i] = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() +
" (" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + ") > ";
result[i] += displayArg(arguments[i]);
result[i] += "\n";
}
return proxied.apply(this, result);
}
})(console.log);
I'm not fully understanding objective but what about something along the lines of the following oversimplified override:
var oldLog = console.log;
console.log= function(){
var d= new Date(),
dateString = // process string
.....
for(var i = 0; i<arguments.length; i++){
oldLog(dateString, arguments[i]);
}
}
TL;DR change the iterator variables so they don't share name, or add a "var" to the loop definition to make sure they don't escape your desired scope.
It turns out that the for loops from (my own) console.log and displayArg were "sharing" the value of the iterator i. This is because by not declaring the iterator variable, the scope was broader than what I needed. To clarify, look at this example:
console.log({isThis:"real life"},"hello","world")
The code from console.log will add a date to the beginning of result[0] and then call displayArg(arguments[0]), arguments[0] being {isThis:"real life"}. That function, will iterate over the objects properties, thus i will be assigned the value isThis. After the function returns, the value of i will not go back to 0. Instead, i will be isThis and as a consequence, the line
result[i] += "\n";
translates to
result[isThis] += "\n"
instead of
result[0] += "\n"
Probably the most sensible solution was to add a var in the for declaration of the iterators. The following code works as expected:
(function (proxied) {
function displayArg(argument){
var result= "";
if(typeof argument == "object") {
result += "{ ";
for (var i in argument) {
result += i + ": ";
result += (displayArg(argument[i]));
result += ", "
}
result = result.substring(0,result.length - 2);
result += " }";
return result;
} else {
return argument;
}
}
console.log = function () {
var result = [];
for (var i in arguments) {
var d = new Date();
result[i] = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() +
" (" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + ") > ";
result[i] += displayArg(arguments[i]);
result[i] += "\n";
}
return proxied.apply(this, result);
}
})(console.log);
Related
{
field_country: ["England", "Netherlands", "India", "Italy"],
field_continent: ["Europe"],
field_group: ["Building", "People", "Landscape"
}
I want to loop over each item and return the key and the array together with ending 'OR' for example:
field_country: "England" OR field_country: "Netherlands"
The last item should not end with 'OR' in the loop. I am not sure what the best process is for this using vanilla JS. So far my code is as follows:
Object.keys(facets).forEach(function(facetKey) {
if (facets[facetKey].length > 1) {
facetResults = facets[facetKey];
for (var i = 0; i < facetResults.length; i ++) {
if (i == 1) {
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
} else {
filter = "'" + facetKey + "'" + ":'" + facetResults[i];
}
}
} else {
filter = "'" + facetKey + "'" + ": " + facets[facetKey] + "'";
return filter;
}
});
I would be very grateful for any assistance.
Thanks in advance.
You can do something like this with Object.entries and Array.reduce if you would like to get the final result in the form of an object:
const data = { field_country: ["England", "Netherlands", "India", "Italy"], field_continent: ["Europe"], field_group: ["Building", "People", "Landscape"] }
const result = Object.entries(data).reduce((r, [k, v]) => {
r[k] = v.join(' OR ')
return r
}, {})
console.log(result)
It is somewhat unclear what is the final format you need to result in but that should help you to get the idea. If ES6 is not an option you can convert this to:
const result = Object.entries(data).reduce(function(r, [k, v]) {
r[k] = v.join(' OR ')
return r
}, {})
So there are is no arrow function etc.
The idea is to get the arrays into the arrays of strings and use the Array.join to do the "replacement" for you via join(' OR ')
Here's the idea. In your code you are appending " or " at the end of your strings starting at index 0. I suggest you append it at the the beginning starting at index 1.
var somewords = ["ORANGE", "GREEN", "BLUE", "WHITE" ];
var retval = somewords[0];
for(var i = 1; i< somewords.length; i++)
{
retval += " or " + somewords[i];
}
console.log(retval);
//result is: ORANGE or GREEN or BLUE or WHITE
Your conditional expression if (i == 1) would only trigger on the second iteration of the loop since i will only equal 1 one time.
Try something like:
if (i < (facetResults.length - 1)) {
// only add OR if this isn't the last element of the array
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
}
Here's your updated code:
Object.keys(facets).forEach(function(facetKey) {
if (facets[facetKey].length > 1) {
facetResults = facets[facetKey];
for (var i = 0; i < facetResults.length; i ++) {
if (i < (facetResults.length - 1)) {
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
} else {
filter = "'" + facetKey + "'" + ":'" + facetResults[i];
}
}
} else {
filter = "'" + facetKey + "'" + ": " + facets[facetKey] + "'";
return filter;
}
});
I have written a code that finds two strings and in return it should tell me if these two strings are existing:
function searchTwoString(data, str1, str2) {
var strX = str1 + " " + strValueX + "\r\n";
var strY = str2 + " " + strValueY;
var strValueX;
var strValueY;
for (var i = 0; i < data.length; i++) {
if (data[i] === str1) {
var strValueX = " exist";
continue;
} else if (data[i] === str2) {
var strValueY = " exist";
break;
}
}
return strX + strY;
}
Achieved result:
str1 undefined
str2 undefined
Expected result:
str1 exist
str2 exist
it tells me my strvalueX & strvalueY are undefined isn't it i have already gave the values in the if statement?
thanks to those who will help out
Here is an answer to your question with comment.
Hope you understand what I'm talking about.
function searchTwoString(data, str1, str2) {
var strX;// = str1 + " " + strValueX + "\r\n";
var strY;// = str2 + " " + strValueY;
var strValueX;
var strValueY;
for (var i = 0; i < data.length; i++) {
if (data[i] === str1) {
// var strValueX = " exist";
// do not define again
strValueX = " exist";
continue;
} else if (data[i] === str2) {
// var strValueY = " exist";
// do not define again
strValueY = " exist";
break;
}
}
// define the value here after strValueX and strValueY is set
strX = str1 + " " + strValueX + "\r\n";
strY = str2 + " " + strValueY;
return strX + strY;
}
The order of your statements is off. In lines 2 and 3, you are using strValueX and strValueY before they are defined. Lines 2 and 3 should be moved to before the return so that they will have the updated values.
I believe there is also a shadowing problem, as in the if statements you are creating new variables with the var keyword (e.g. var strValueX = " exist";). You will want to remove var from the if statements so that it updates the values of the outer variables.
I'm turning a string into an object, then looping over that object. For some reason, if the string is semi-correctly formatted and I don't do the first two steps (replacing the parentheses with curly brackets) it works fine.
However, the replacement puts single ' instead of " (although it still parses without error). The parse misses putting the second id underneath the employeeType, and mistakenly puts it under employee.
https://codepen.io/MrMooCats/pen/zwpQGa
var str = "(id,created,employee(id,firstname,employeeType(id),lastname),location)";
str = str.replace(/[(]/g, "{"); // Possible problem line?
str = str.replace(/[)]/g, "}"); // Possible problem line?
str = str.replace(/([A-z])\s*{/g, "$1\":{");
str = str.replace(/([A-z])\s*([},])/g, "$1\":null$2");
str = str.replace(/({)/g, "{\"");
str = str.replace(/(,)/g, ",\"");
var objectStr = JSON.parse(str); // Object created, but wrong
var objectOutput = function(obj, counter) {
for(var i in obj) {
console.log(Array(counter+1).join("-") + " " + i);
if(obj.hasOwnProperty(i)){
if (obj[i] != null) {
objectOutput(obj[i], counter+1);
} else {
counter = 0;
}
}
}
};
objectOutput(objectStr, 0);
Actual output:
" id"
" created"
" employee"
"- id"
" firstname"
" employeeType"
"- id"
" lastname"
" location"
Expected Output
" id"
" created"
" employee"
"- id"
"- firstname"
"- lastname"
"- employeeType"
"-- id"
" location"
To get desired output you need to fix your objectOutput functrion:
// Works fine if the ( are { instead and remove the first two lines
var str = "(id,created,employee(id,firstname,employeeType(id),lastname),location)";
str = str.replace(/[(]/g, "{"); // Possible problem line?
str = str.replace(/[)]/g, "}"); // Possible problem line?
str = str.replace(/([A-z])\s*{/g, "$1\":{");
str = str.replace(/([A-z])\s*([},])/g, "$1\":null$2");
str = str.replace(/({)/g, "{\"");
str = str.replace(/(,)/g, ",\"");
var objectStr = JSON.parse(str); // Object created, but wrong
var objectOutput = function(obj, counter) {
for (var i in obj) {
console.log(Array(counter + 1).join("-") + " " + i);
if (obj.hasOwnProperty(i)) {
if (obj[i] != null) {
objectOutput(obj[i], counter + 1);
}
}
}
};
objectOutput(objectStr, 0);
I would also change regex this way:
var str = "(id,created,employee(id,firstname,employeeType(id),lastname),location)";
str = str.replace(/\(/g, "{").replace(/\)/g, "}");
str = str.replace(/([_a-zA-Z][_a-zA-Z0-9]*)\s*([,{}])/g, function(m, name, x){
return '"'+name+'":' + (x != '{' ? 'null' : '') + x;});
var objectStr = JSON.parse(str);
var objectOutput = function(obj, counter) {
for (var i in obj) {
console.log(Array(counter + 1).join("-") + " " + i);
if (obj.hasOwnProperty(i)) {
if (obj[i] != null) {
objectOutput(obj[i], counter + 1);
}
}
}
};
objectOutput(objectStr, 0);
I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}
now when I put my own Object in alert function I see
[Object object]
that is pointless information. is there any way using reflection to get all fields and values of those fields?
JSON.stringify is often times builtin and can serialize most objects you pass to it.
That said, you should probably just use a debugger or console.log instead of alert-ing things.
Here is one of many. But better to use console.log() then alert
function objectToString(o){
var parse = function(_o){
var a = [], t;
for(var p in _o){
if(_o.hasOwnProperty(p)){
t = _o[p];
if(t && typeof t == "object"){
a[a.length]= p + ":{ " + arguments.callee(t).join(", ") + "}";
}
else {
if(typeof t == "string"){
a[a.length] = [ p+ ": \"" + t.toString() + "\"" ];
}
else{
a[a.length] = [ p+ ": " + t.toString()];
}
}
}
}
return a;
}
return "{" + parse(o).join(", ") + "}";
}
sure, maybe something like
function alertObject(0){
var str = "";
for(i in o)
str += i + " " + o[i] + "\n";
alert(str);
}
Edit :: Note this is just a silly little example.