How to change JSON String data to JSON Number data - javascript

Good day everyone, I'm trying to obtain the numerical value of 'review' what happens is that in the JSON it returns it as a String and therefore I cann't perform a sum that I did, resulting in a meaningless value
The objective is that, when someone makes a comment about an X product, the data is saved in Firebase in a JSON, the problem is that 'review' is saved as a String and not saved as a number
Is there a way to take this single piece of data and convert it to number?
This is the JSON response
"[{\"review\":\"4\",\"comment\":\"Good product \",\"name\":\"SnowFall\",\"image\":\"https://lh3.googleusercontent.com\",\"method\":\"google\"}]"
This is my TypeScript
callback(i, totalReviews) {
if (!this.render) {
this.render = true;
let globalRating = 0;
let globalReviews = 0;
setTimeout(function () {
totalReviews.forEach((review, index) => {
globalRating += review.length;
for (const i in review) {
globalReviews += review[i].review;
console.log("globalReviews", globalReviews);
}
})
console.log("Raiting", globalRating);
console.log("Reviews", globalReviews);
let averageReviews = Math.round(globalReviews / globalRating);
let precentage = Math.round(globalReviews * 100 / (globalRating * 5));
$(".globalRating").html(globalRating);
$(".percentage").html(precentage);
let averageRating = DinamicReviews.fnc(averageReviews);
$(".br-theme-fontawesome-stars").html(`
<select class="ps-rating reviewsOption" data-read-only="true"></select>
`)
for (let i = 0; i < averageRating.length; i++) {
$(".reviewsOption").append(`
<option value="${averageRating[i]}">${i + 1}</option>
`)
}
Rating.fnc();
}, i * 10)
}
}
This is how it is saved in FireBase FireBase RealTime Database
This is how it looks on my FrontEnd
FrontEnd

There is a line where you assign the .review value to the globalReviews variable as this is using += this shall be concatenating the string and that is the problem you are facing.
If you change that same line to: globalReviews += +review[i].review;
This will fix the error.
The reason why adding a + sign in front of a variable works is because this sign is known as the Unary Plus Operator which converting the value to a number or in case the store value is not a number it will convert following the Unary Plus Operator documentation
To make this code safe and thus not add a possible NaN you can failsafe to 0 by using the following syntax globalReviews += +review[i].review || 0;

Related

Converting time to hexidecimal then to string using javascrit

I am trying to convert present time to hexidecimal then to a regular string variable.
For some reason I can only seem to produce an output in double quotes such as "result" or an object output. I am using Id tags to identify each div which contains different messages. They are being used like this id="somename-hexnumber". The code if sent from the browser to a node.js server and the ID is split up into two words with first section being the person's name then "-" is the split key then the hexidecimal is just the div number so it is easy to find and delete if needed. The code I got so far is small but I am out of ideas now.
var thisRandom = Date.now();
const encodedString = thisRandom.toString(16);
var encoded = JSON.stringify(encodedString);
var tIDs = json.name+'-'+encoded;
var output = $('<div class="container" id="'+tIDs+'" onclick="DelComment(this.id, urank)"><span class="block"><div class="block-text"><p><strong><'+json.name+'></strong> '+json.data+'</p></div></div>');
When a hexidecimal number is produced I want the output to be something like 16FE67A334 and not "16FE67A334" or an object.
Do you want this ?
Demo: https://codepen.io/gmkhussain/pen/QWEdOBW
Code below will convert the time/number value d to hexadecimal.
var thisRandom = Date.now();
function timeToHexFunc(x) {
if ( x < 0) {
x = 0xFFFFFFFF + x + 1;
}
return x.toString(16).toUpperCase();
}
console.log(timeToHexFunc(thisRandom));

How to have a function repeat until its value is the same as another function?

I am making a program to present to the other members of the CyberPatriots club I am in. I want someone to enter a password and have it iterate through all the possible ways until it gets it, my idea is that it counts in base 10, which is converted to base 95 using asci instead of numbers, the problem I have is having it count until the passwords match. The code so far is only the converting part.
function generate(state) {
const printables = ' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
var ones = state % printables.length
var newstate = Math.floor(state / printables.length)
if (newstate !== 0) {
return generate(newstate) + printables[ones]
} else {
return printables[ones]
}
}
console.log(generate(10000))
Thanks!

Is there Any Way to Convert Mongo ObjectId into string by javascript/jquery

Is it possible to convert mongo objectId into string.
The above pictures shows data i received and shown in console.I need id value in string form .but ObjectId is returning as object
In Database id is look like this- 565d3bf4cefddf1748d1fc5e -objectId and i need id exactly like this –
According to the Mongo documentation:
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.
You can check it out here: https://docs.mongodb.org/manual/reference/object-id/
So in javascript you could do something like this.
var mId = {
Timestamp:1448950573,
Machine:13565407,
Pid:1756,
Increment:8888962
};
function getId(mongoId) {
var result =
pad0(mongoId.Timestamp.toString(16), 8) +
pad0(mongoId.Machine.toString(16), 6) +
pad0(mongoId.Pid.toString(16), 4) +
pad0(mongoId.Increment.toString(16), 6);
return result;
}
function pad0(str, len) {
var zeros = "00000000000000000000000000";
if (str.length < len) {
return zeros.substr(0, len-str.length) + str;
}
return str;
}
console.log(getId(mId))
It produces "565d3b2dcefddf06dc87a282" which was not exactly the id you had, but that might just be a tweak or i was working with different data :D.
EDIT
Added a padding function so that zeros are not truncated.
Hope that helps
EDIT:
I assume you are using c# to connect to and serve documents from the mongo DB. In that case, there is a driver that also supports toString().
Here is an example using the mongo csharp driver:
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
// ...
string outputFileName; // initialize to the output file
IMongoCollection<BsonDocument> collection; // initialize to the collection to read from
using (var streamWriter = new StreamWriter(outputFileName))
{
await collection.Find(new BsonDocument())
.ForEachAsync(async (document) =>
{
using (var stringWriter = new StringWriter())
using (var jsonWriter = new JsonWriter(stringWriter))
{
var context = BsonSerializationContext.CreateRoot(jsonWriter);
collection.DocumentSerializer.Serialize(context, document);
var line = stringWriter.ToString();
await streamWriter.WriteLineAsync(line);
}
});
}
ORIGINAL:
These are Mongo ObjectId's and if you haven't already deserialised the document they should support a toString method that will return a hexadecimal string.
but if you want this applied to the whole document, using JSON.stringify(MogoDocument) should deserialize this for you into a plain object.

Generating a unique ID in Javascript

I want to implement a saving system similar to Imgur where if a user presses a button a unique 5 character value is returned. Here is what I have so far:
The database backend uses auto-incrementing ID's starting at 5308416. I use a modified Radix function (see below) to convert these numerical ID's into characters. I use a reverse function to lookup character ID's back to numerical database ID's.
function genID (value)
{
var alphabet = "23456789BCDFGHJKLMNPRSTVWXYZbcdfghjkmnpqrstvwxyz";
var result = "";
var length = alphabet.length;
while (value > 0)
{
result = alphabet[value % length] + result;
value = Math.floor (value / length);
}
return result;
}
The problem is that these generated ID's are very much predictable. My question is, how can I make the generated ID's seem random but still unique (so I can look them up in the database as numbers). I was thinking of using some encryption algorithm but not sure where to start. Any help or suggestions would be appreciated (maybe there is a better way of doing this also).
Do you have to be able to go both ways (i.e. convert an integer to it's hash and back again)? If you can store the hash and lookup the content that way, then it's relatively easy to create a function that produces a hard-to-guess, but complete hash space. You use primes to generate a sequence that only repeats once all possible permutations are exhausted.
The following PHP example is from my own code, adapted from this site:
function hash($len = 6) {
$base = 36;
$gp = array(1,23,809,28837,1038073,37370257 /*,1345328833*/);
$maxlen = count($gp);
$len = $len > ($maxlen-1) ? ($maxlen-1) : $len;
while($len < $maxlen && pow($base,$len) < $this->ID) $len++;
if($len >= $maxlen) throw new Exception($this->ID." out of range (max ".pow($base,$maxlen-1).")");
$ceil = pow($base,$len);
$prime = $gp[$len];
$dechash = ($this->ID * $prime) % $ceil;
$hash = base_convert($dechash, 10, $base);
return str_pad($hash, $len, "0", STR_PAD_LEFT);
}
It would be easy enough to implement that in JavaScript, but ideally you wouldn't need too - you'd have an insert trigger on your table that populated a hash field with the result of that algorithm (adapted for SQL, of course).
A non-predictable, but unique ID can be made by combining your server-side auto-incrementing number with either a current date/time nugget or with a random number. The server-side auto-incrementing number guarantees uniqueness and the date/time nugget or random number removes the predictability.
For a unique ID in string form that takes the server-side unique number as input and where you add the date/time nugget on the client you can do this:
function genID(serverNum) {
return(serverNum + "" + (new Date).getTime());
}
Or using a random number:
function genID(serverNum) {
return(serverNum + "" + Math.floor(Math.random() * 100000));
}
But, it might be best to add the date/time element on the server and just store that whole unique ID in the database there.

Best way to generate unique ids client-side (with Javascript)

I need to generate unique ids in the browser. Currently, I'm using this:
Math.floor(Math.random() * 10000000000000001)
I'd like to use the current UNIX time ((new Date).getTime()), but I'm worried that if two clients generate ids at the exact same time, they wouldn't be unique.
Can I use the current UNIX time (I'd like to because that way ids would store more information)? If not, what's the best way to do this (maybe UNIX time + 2 random digits?)
you can create a GUID using the following links:
http://softwareas.com/guid0-a-javascript-guid-generator
Create GUID / UUID in JavaScript?
This will maximise your chance of "uniqueness."
Alternatively, if it is a secure page, you can concatenate the date/time with the username to prevent multiple simultaneous generated values.
https://github.com/uuidjs/uuid provides RFC compliant UUIDs based on either timestamp or random #'s. Single-file with no dependencies, supports timestamp or random #-based UUIDs, uses native APIs for crypto-quality random numbers if available, plus other goodies.
In modern browser you can use crypto:
var array = new Uint32Array(1);
window.crypto.getRandomValues(array);
console.log(array);
var c = 1;
function cuniq() {
var d = new Date(),
m = d.getMilliseconds() + "",
u = ++d + m + (++c === 10000 ? (c = 1) : c);
return u;
}
Here is my javascript code to generate guid. It does quick hex mapping and very efficient:
AuthenticationContext.prototype._guid = function () {
// RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or
// pseudo-random numbers.
// The algorithm is as follows:
// Set the two most significant bits (bits 6 and 7) of the
// clock_seq_hi_and_reserved to zero and one, respectively.
// Set the four most significant bits (bits 12 through 15) of the
// time_hi_and_version field to the 4-bit version number from
// Section 4.1.3. Version4
// Set all the other bits to randomly (or pseudo-randomly) chosen
// values.
// UUID = time-low "-" time-mid "-"time-high-and-version "-"clock-seq-reserved and low(2hexOctet)"-" node
// time-low = 4hexOctet
// time-mid = 2hexOctet
// time-high-and-version = 2hexOctet
// clock-seq-and-reserved = hexOctet:
// clock-seq-low = hexOctet
// node = 6hexOctet
// Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
// y could be 1000, 1001, 1010, 1011 since most significant two bits needs to be 10
// y values are 8, 9, A, B
var guidHolder = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
var hex = '0123456789abcdef';
var r = 0;
var guidResponse = "";
for (var i = 0; i < 36; i++) {
if (guidHolder[i] !== '-' && guidHolder[i] !== '4') {
// each x and y needs to be random
r = Math.random() * 16 | 0;
}
if (guidHolder[i] === 'x') {
guidResponse += hex[r];
} else if (guidHolder[i] === 'y') {
// clock-seq-and-reserved first hex is filtered and remaining hex values are random
r &= 0x3; // bit and with 0011 to set pos 2 to zero ?0??
r |= 0x8; // set pos 3 to 1 as 1???
guidResponse += hex[r];
} else {
guidResponse += guidHolder[i];
}
}
return guidResponse;
};
You can always run a test against existing IDs in the set to accept or reject the generated random number recursively.
for example:
const randomID = function(){
let id = Math.floor(Math.random() * 10000000000000001) + new Date();
if (idObjectArray.contains(id)) {
randomID;
} else {
idObjectArray.push(id);
}
};
This example assumes you would just be pushing the id into a 1D array, but you get the idea. There shouldn't be many collisions given the uniqueness of the random number with the date, so it should be efficient.
There are two ways to achieve this
js const id = Date.now().toString()
While this does not guarantee uniqueness (When you are creating multiple objects within 1ms), this will work on a practical level, since it is usually not long before the objects on the client are sent to a real server.
If you wanted to create multiple records withing 1ms, I suggest using the code below
const { randomBytes } = require("crypto");
// 32 Characters
const id = randomBytes(16).toString("hex");
It works similar to a uuid4 without needing to add an external library (Assuming you have access to NodeJs at some point)

Categories