String.padStart() not applying in Angular function - javascript

I have an angular function which receives a number from a GET request and then will encode that number as base 64. I am trying to use the padStart function outlined here, but when I log the string after calling the function, the string is not padded. Any ideas why?
Angular:
$scope.generateCode = function(){
var number = autogenNumber(); //Pull the number
number.then(function (result) { //Then increment up and convert
var working_str = result.toString();
console.log("The pre padded string is", working_str);
working_str.padStart(8, '1234');
console.log("The padded string is now", working_str, typeof working_str);
})
};

A string is immutable. You have to reassign
working_str = working_str.padStart(8, '1234');

Related

Working with memory to fetch string yields incorrect result

I am following the solutions from here:
How can I return a JavaScript string from a WebAssembly function
and here:
How to return a string (or similar) from Rust in WebAssembly?
However, when reading from memory I am not getting the desired results.
AssemblyScript file, helloWorldModule.ts:
export function getMessageLocation(): string {
return "Hello World";
}
index.html:
<script>
fetch("helloWorldModule.wasm").then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, {imports: {}})
).then(results => {
var linearMemory = results.instance.exports.memory;
var offset = results.instance.exports.getMessageLocation();
var stringBuffer = new Uint8Array(linearMemory.buffer, offset, 11);
let str = '';
for (let i=0; i<stringBuffer.length; i++) {
str += String.fromCharCode(stringBuffer[i]);
}
debugger;
});
</script>
This returns an offset of 32. And finally yields a string that starts too early and has spaces between each letter of "Hello World":
However, if I change the array to an Int16Array, and add 8 to the offset (which was 32), to make an offset of 40. Like so:
<script>
fetch("helloWorldModule.wasm").then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, {imports: {}})
).then(results => {
var linearMemory = results.instance.exports.memory;
var offset = results.instance.exports.getMessageLocation();
var stringBuffer = new Int16Array(linearMemory.buffer, offset+8, 11);
let str = '';
for (let i=0; i<stringBuffer.length; i++) {
str += String.fromCharCode(stringBuffer[i]);
}
debugger;
});
</script>
Then we get the correct result:
Why does the first set of code not work like its supposed to in the links I provided? Why do I need to change it to work with Int16Array to get rid of the space between "H" and "e" for example? Why do I need to add 8 bytes to the offset?
In summary, what on earth is going on here?
Edit: Another clue, is if I use a TextDecoder on the UInt8 array, decoding as UTF-16 looks more correct than decoding as UTF-8:
AssemblyScript uses utf-16: https://github.com/AssemblyScript/assemblyscript/issues/43
Additionally AssemblyScript stores the length of the string in the first 32 or 64 bits.
That's why my code behaves differently. The examples in the links at the top of this post were for C++ and Rust, which do string encoding differently

Getting undefined instead of string

The output of this program is undefined instead of string name.
I am taking a date as input to the program and comparing the date with the existing dates of president array. In case if the date matches then i want to return the president name for that particular date
process.stdin.resume();
process.stdin.setEncoding('utf8');
var stdin = '';
process.stdin.on('data', function (chunk) {
//printing the value returned by presidentOnDate function
console.log(JSON.stringify(presidentOnDate(chunk)));
});
//This is presidents array
var presidents = [
{"number":32,"president":"Franklin D. Roosevelt","took_office":"1933-03-04","left_office":"1945-04-12"},
{"number":33,"president":"Harry S. Truman","took_office":"1945-04-12","left_office":"1953-01-20"},
{"number":34,"president":"Dwight D. Eisenhower","took_office":"1953-01-20","left_office":"1961-01-20"},
{"number":35,"president":"John F. Kennedy","took_office":"1961-01-20","left_office":"1963-11-22"},
{"number":36,"president":"Lyndon B. Johnson","took_office":"1963-11-22","left_office":"1969-01-20"},
{"number":37,"president":"Richard Nixon","took_office":"1969-01-20","left_office":"1974-08-09"},
{"number":38,"president":"Gerald Ford","took_office":"1974-08-09","left_office":"1977-01-20"},
{"number":39,"president":"Jimmy Carter","took_office":"1977-01-20","left_office":"1981-01-20"},
{"number":40,"president":"Ronald Reagan","took_office":"1981-01-20","left_office":"1989-01-20"},
{"number":41,"president":"George H. W. Bush","took_office":"1989-01-20","left_office":"1993-01-20"},
{"number":42,"president":"Bill Clinton","took_office":"1993-01-20","left_office":"2001-01-20"},
{"number":43,"president":"George W. Bush","took_office":"2001-01-20","left_office":"2009-01-20"},
{"number":44,"president":"Barack Obama","took_office":"2009-01-20","left_office":"2017-01-20"}
];
//PresidentOnDate function which should return a president name based on input date
function presidentOnDate(date) {
var output="";
for(var i=0;i<presidents.length;i++){
//console.log(presidents[i].took_office);
if((presidents[i].took_office)==date){
output+=presidents[i].president;
}
}
return output;
}
I think the problem is you are passing in a buffer instead of a string.
Try changing the chunk buffer to a string before passing it to presidentOnDate.
So instead of presidentOnDate(chunk) try presidentOnDate(chunk.toString())
Try this function it's working fine.
problem you facing when you take input it take \r\n also so when you compare both you get false that y output showing null.
EX:input string: "2009-01-20\r\n" compare with : took_office: "2009-01-20" => result false
EX: input string with trim: "2009-01-20" compare with : took_office: "2009-01-20" => result True
change only : (presidents[i].took_office) ==date.trim()
function presidentOnDate(date) {
var output="";
for(var i=0;i<presidents.length;i++){
if((presidents[i].took_office) ==date.trim()){
output+= presidents[i].president;
}
}
return output;
}

Assign text to variable inside the String

I am saving string into mongoDB with preset variable as
'Current time is ${time}'
After that I am retrieving somewhere else this string and would like to assign value to time
It would look something like this
const time = '15:50'
const response = result //saves string retreived from mongo
res.json({
response: response
})
But that returns 'Current time is ${time}' instead of 'Current time is 15:50'
I am aware that the string should be in `` instead of single quotes for variable to work, not sure though how to implement that as output from mongo
Anyone could point me to correct direction?
An alternative is to pass the string and parameters to a function and reduce over the parameters object:
var str = 'Current time is ${time}';
var params = { time: '13:30' };
function merge(str, params) {
return Object.keys(params).reduce((out, key) => {
return str.replace(`\${${key}}`, params[key]);
}, '');
}
console.log(merge(str, params));
And this is an example of interpolation magic, as mentioned in other answer ;) Note, than even without the evil() ;)
var time = '15:50'
var response = 'Current time is ${time}'
var converted = (_=>(new Function(`return\`${response}\`;`))())()
console.log(converted)
Interpolation is not performed on a string variable that happens to contain a template literal placeholder. In order for interpolation to happen, you must have a literal string in the code, enclosed in back ticks with a placeholder:
let time = '15:50';
let message = `Current time is ${time}`
console.log(message); // "Current time is 15:50"
If you must store strings in your database, you'll have to come up with your own mechanism for interpolating your placeholders.

From Javascript Int to a Java String

So I have a variable in Javascript that can be both String and int, I need to send it to a java method. I though that, since it's easier to change a number into a string instead of the opposite, I set the variable into a string. I'm gonna post some code
This is obviously the javascript, the variable valore is the one that can be both Int and string
$(".save").click(function() {
var valore = $("#valore").val();
var connettore = $("#connettore option:selected").text().split(" ").join("");
$.get("select"+connettore+".do", {
nomecampo: $("#colonnaRiferim").val().toLowerCase(),
valore: valore
}, function (data) {
for (var i = 0; i < data.connettore.length; i++) {
var conn = data.connettore[i];
}
}
);
This is the Java function
#RequestMapping("selectCompensi")
#ResponseBody
#Transactional
public ModelWrapper<List<TracciatoCompensi>> selectCompensi(#RequestParam String nomecampo,
#RequestParam String valore){
Session s = hibernateFactory.getCurrentSession();
ModelWrapper<List<TracciatoCompensi>> resp = new ModelWrapper<List<TracciatoCompensi>>();
Criteria c = s.createCriteria(TracciatoCompensi.class)
.add(Restrictions.eq(nomecampo, valore));
List<TracciatoCompensi> aList = (List<TracciatoCompensi>) c.list();
Query query = s.createSQLQuery("INSERT INTO tracciato_compensi_clone (CODICEORDINE, CODICESERVIZIO, CODICEUNIVOCOCOMPONENTE, COEFFICIENTECANONEMESE, "+nomecampo+", compensi1, rev, mod_time, mod_user) ("
+"SELECT CODICEORDINE, CODICESERVIZIO, CODICEUNIVOCOCOMPONENTE, COEFFICIENTECANONEMESE, "+nomecampo+", "+nomecampo+", rev, mod_time, mod_user FROM tracciato_compensi WHERE "+nomecampo+" = '"+valore+"')");
resp.put("connettore", aList);
query.executeUpdate();
return resp;
}
You can ignore the Query, that stuff works, as so does the criteria and the rest. My problem seems obvious, if valore is numeric, then the function crash,
I tried to add a random character to the number, and I tried to convert it using toString() into javascript but even if I use the isNumeric() function of jquery and it says that it isn't numeric, it still crashes
The method you're looking for probably is String.valueOf(Object):
String valore1 = "5";
System.out.println(String.valueOf(valore1));
int valore2 = 5;
System.out.println(String.valueOf(valore2));
gives:
5
5
in the console.

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.

Categories