Chaining join method after push doesn't works - ecmascript-6

let data = {a:5,b:6,c:7,d:8}
let price = 15
let urlParams = Object.entries(data)
.map(([key,value])=>`${key}=${value}`)
.push("price="+price)
.join("&")
I need to get the output as a string
"a=5&b=6&c=7&d=8&price=15"
The return result of push will be the length of the array, so when i call a join method it will return an error. Is there any work around for this
Thanks in advance!!

assign urlParams to a variable
push your string onto it
then join("&")
Array.push modifies the array because it is mutating.

Your push will mutate the array directly and that could potentially lead to error-prone code.
You can use concat since it returns a new array.
let data = {a:5,b:6,c:7,d:8}
let price = 15
let urlParams = Object.entries(data)
.map(([key,value])=>`${key}=${value}`)
.concat("price="+price)
.join("&")
console.log(urlParams);

Related

Jsony newHook has `SIGSEGV: Illegal storage access. (Attempt to read from nil?)` when deserializing into ref-objects

I am writing a web-application and am deserializing via jsony into norm-model-object types.
Norm-model-types are always ref objects. Somehow my code which is very similar to the default example in jsony's github documentation does not compile. Instead I receive the error SIGSEGV: Illegal storage access. (Attempt to read from nil?).
See here my code sample
import std/[typetraits, times]
import norm/[pragmas, model]
import jsony
const OUTPUT_TIME_FORMAT* = "yyyy-MM-dd'T'HH:mm:ss'.'ffffff'Z'"
type Character* {.tableName: "wikientries_character".} = ref object of Model
name*: string
creation_datetime*: DateTime
update_datetime*: DateTime
proc parseHook*(s: string, i: var int, v: var DateTime) =
##[ jsony-hook that is automatically called to convert a json-string to datetime
``s``: The full JSON string that needs to be serialized. Your type may only be a part of this
``i``: The index on the JSON string where the next section of it starts that needs to be serialized here
``v``: The variable to fill with a proper value]##
var str: string
s.parseHook(i, str)
v = parse(s, OUTPUT_TIME_FORMAT, utc())
proc newHook*(entry: var Character) =
let currentDateTime: DateTime = now()
entry.creation_datetime = currentDateTime # <-- This line is listed as the reason for the sigsev
entry.update_datetime = currentDateTime
entry.name = ""
var input = """ {"name":"Test"} """
let c = input.fromJson(Character)
I don't understand what the issue appears to be here, as the jsony-example on its github page looks pretty similar:
type
Foo5 = object
visible: string
id: string
proc newHook*(foo: var Foo5) =
# Populates the object before its fully deserialized.
foo.visible = "yes"
var s = """{"id":"123"}"""
var v = s.fromJson(Foo5)
doAssert v.id == "123"
doAssert v.visible == "yes"
How can I fix this?
The answer lies in the fact that norm-object-types are ref objects, not normal (value) objects (Thanks to ElegantBeef, Rika and Yardanico from the nim-discord to point this out)! If you do not explicitly 'create' a ref-type at one point, the memory for it is never allocated since the code doesn't do the memory allocation for you unlike with value types!
Therefore, you must initialize/create a ref-object first before you can use it, and Jsony does not take over initialization for you!
The correct way to write the above newHook thus looks like this:
proc newHook*(entry: var Character) =
entry = new(Character)
let currentDateTime: DateTime = now()
entry.creation_datetime = currentDateTime
entry.update_datetime = currentDateTime
entry.name = ""

Parsing string data response

I am stuck in parsing a data response receiving from some third party vendor.
response is something like:-
data: ()(responseCode='A01', responseMessage='Approved', accountNumber='qwerty');
I have tried several ways of parsing/stringify but it does not provide me a JSON response. I tried weird combinations of Querystring functions as well but that did not help.
I am badly stuck in this.
I will post a workaround it might not be efficient but will give you the result.
var data = "data: ()(responseCode='A01', responseMessage='Approved', accountNumber='qwerty');";
var temp = data.substring(8,);
temp = temp.replace("(","{");
temp = temp.replace(")","}");
temp = temp.replace(/=/g,":");
temp = temp.replace(";","");
temp = eval('(' + temp + ')');
var Result = JSON.stringify(temp)
Result : {"responseCode":"A01","responseMessage":"Approved","accountNumber":"qwerty"}
You can use regex to convert it to a valid JSON structure.
let data = `data: ()(responseCode='A01', responseMessage='Approved', accountNumber='qwerty');`;
let modified = data
.replace(/\s/g,'')
.replace("data:()(",'{\'')
.replace(");",'}')
.replace(/=/g,"':")
.replace(/,/g,",'")
.replace(/'/g,'"')
let json = JSON.parse(modified);
console.log(json)

how to do angular update current user value of username in local storage

how to update local storage of a current User for only username when i update username its not reflecting in localstorage,am able to see the change in component page in console am getting null value for item and in console application localstorage null is stored key and value is {username:gasd} its not joining in that json. by using angular6
let item =localStorage.getItem(this.currentUser);
console.log(item);
let myobj = {username:changeValue};
localStorage.setItem(item, JSON.stringify(myobj));
Think of localStorage as a key-value dictionary.
You use string keys to get/set string values. (more on that in MDN docs)
So for objects you can do for example:
let myObj = {};
my["myKey"] = "myVal"; // note that in objects, values don't need to be strings
my["myKey2"] = 2;
my["myKey3"] = {};
In localStorage however it's strings on both sides:
localStorage.setItem("currentUser", {username: "ganes"}); // BAD
localStorage.setItem({username: "ganes"}, "someValue"); // BAD
localStorage.getItem({username: "ganes"}) // BAD
let currentUserDataStr = localStorage.getItem("currentUser"); // GOOD
// something along these lines
let currentUserData = JSON.parse(currentUserDataStr);
// do some mutation on currentUserData
currentUserData.currentUser = "ganesNew"
let newUserDataStr = JSON.stringify(currentUserData)
localStorage.setItem("currentUser", newUserDataStr); // GOOD

endsWith with array in ES6

I learning ES6 and try to use new for me endsWith. Before this I used includes in some of my scripts, and I thought that mechanic will be same. I picked a casual task: I have domains list and want to filter all "cn" domains. Logic is:
let ends = [".cn",".tw",".jp"]
for(let i=0;i<arrayOfDomains.length;i++){
const host = /https?:\/\/(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]+/.exec(arrayOfDomains[i])[0];
console.log(host.endsWith(ends))
}
and result of console.log all false. Is there a way to use array in endsWith?
No, there isn't a way to use an array in endsWith, one option is to declare another function that uses the ends array and host variable as parameters to check it.
You can try something like this:
let ends = [".cs", ".com"];
let host = "www.page.com";
let hostEndsWith = (host, ends) => {
let value = false;
value = ends.some(element => {
return host.endsWith(element);
});
console.log(value);
};
hostEndsWith(host, ends);
You can copy that code in JSFiddle to test it.
Here is the information about the endsWith function endsWith informartion
I hope this helps you!

AS3 Custom string formula parser

My goal is to create some kind of Parser to parse string formulas, similar to Excel formulas.
Formula string example (barcode example) -
"CONCAT('98', ZEROFILL([productNumber],5,'0'), ZEROFILL(EQUATION([weightKG]*1000),5,'0'))"
where
'98' - String
[productNumber] and [weightKG] - are variables that can be changed
CONCAT, ZEROFILL and EQUATION are methods which exist in class
For this formula with variables [productNumber] = '1' and [weightKG] = 0.1 result must be
'980000100100'
The question is how to split/parse whole string to parts and detect methods, variables and string values?
Another idea occurred, while i was typing - is to store whole formula in XML format.
Thank You.
You can use String.split() to get an array of substrings.
However, using your example, calling split(",") would give you the following array:
[0]=CONCAT('98'
[1]= ZEROFILL([productNumber]
[2]=5
[3]='0')
[4]= ZEROFILL(EQUATION([weightKG]*1000)
[5]=5
[6]='0'))
That doesn't seem like it will be very helpful for your project. Instead, you might think about creating a parse() function with some logic to find useful substrings:
function parse(input:String):Array {
var firstParen:int = input.indexOf("(");
var lastParen:int = input.lastIndexOf(")");
var formulaName:String = input.substring(0, firstParen);
var arguments:String = input.substring(firstParen, lastParen);
var argumentList:Array = parseArgs(arguments);
var result:Array = new Array();
result.push(formulaName);
//Recursively call parse() on the argumentList
foreach (var elem:* in argumentList) {
result.push(elem); //Could be string or array.
}
}
function parseArgs(input:String):Array {
// Look for commas that aren't enclosed inside parenthesis and
// construct an array of substrings based on that.
//A regex may be helpful here, but the implementation is left
//as an exercise for the reader.
}