Convert function parameter in string into parameter in object - javascript

I am using node.js.
I have a function that can be called this way;
add_row({location:'L1', row_name:'r1', value:'18.4'});
I have a string like this;
var str_param = "location:'L1', row_name:'r1', value:'18.4'";
I tried to do something like this to keep my code simple;
add_row(str_param);
It did not work. What is a good way to use str_param to call add_row?

You could convert the string to an object that the function accepts.
function toObj(str) {
const a = str.split(/,.?/g);
return a.reduce((p, c) => {
const kv = c.replace(/'/g, '').split(':');
p[kv[0]] = kv[1];
return p;
}, {});
}
toObj(str); // { location: "L1", row_name: "r1", value: "18.4" }
DEMO

I think this may be your issue:
{location:'L1', row_name:'r1', value:'18.4'} // Object
var str_param = "location:'L1', row_name:'r1', value:'18.4'"; // Not object
var str_param = "{location:'L1', row_name:'r1', value:'18.4'}"; // Object String
I do not use Node JS but just taking a shot in dark. If not you could just make function like:
function addRow(pLocation, pRowName, pValue) {
var row = {
location: pLocation,
row_name: pRowName,
value: pValue
}
// Logic ....
}
If that does not work try using Object string and look at function ParseJSON I believe it's called.

Related

Javascript: call object method using string only

This code doesn't work.
var Modal = {
init: function() {
console.log("test");
}
}
var objMethod = "Modal.init";
window[objMethod]();
I saw some answers that it can be called using this but I want to know how it can be called without using the object.
Modal["init"]();
Thank you!
To call a namespaced function, you need to use a multidimensional array. In this case it would be window['Modal']['init'](), which can also be expressed by splitting the objMethod string and using array indices:
var arr = objMethod.split(".");
window[arr[0]][arr[1]]();
var Modal = {
init: function() {
console.log("test");
}
}
var objMethod = "Modal.init";
var arr = objMethod.split(".");
window[arr[0]][arr[1]]();

Save key=>value style with ngStorage/localstorage

In my Ionic app I've added the plugin 'ngStorage' and it comes with a little demo code:
var add = function (thing) {
$localStorage.things.push(thing);
}
This works exactly as told. I add("foo") it, and do getAll() and the value is there. I remove the add(), but keep the getAll(), I still have the value "foo" (as expected).
This isn't very usefull for me, I want to access it with keys, so I've made the following:
var addByKey = function (key, value) {
$localStorage.things[key] = value;
// Or, I've also tried:
$localStorage.things.key = value;
}
When I do the addByKey("foo","bar") and then the getAll() I get the values exactly as I want. When I remove the addByKey() and reload, I expect it to still remember the set information, but it doesn't exist. However, the first attempt via the add() function still exists, "foo" is still there (meaning the array doesnt reset).
How do I make a key->value type of structure?
In case it's usefull:
.factory ('StorageService', function ($localStorage) {
$localStorage = $localStorage.$default({
things: []
});
var _getAll = function () {
return $localStorage.things;
};
var _add = function (thing) {
$localStorage.things.push(thing);
}
var _addByKey = function (thing, value) {
$localStorage.things[key] = value;
// Or, I've also tried:
$localStorage.things.key = value;
}
return {
getAll: _getAll,
add: _add,
addByKey: _addByKey
};
})
Assuming that you want a key value storage system you can simply use an object instead of an array so that every key can be set as a property of this object.
.factory('StorageService', function($localStorage) {
$localStorage = $localStorage.$default({
things: {}
});
var _getAll = function() {
return $localStorage.things;
};
var _addByKey = function(thing, value) {
$localStorage.things[thing] = value;
}
return {
getAll: _getAll,
addByKey: _addByKey
};
})
However, assuming that you want to keep a reference of all values on the main collection and access them through keys, you can consider using an object to store the things intead of an array. So that you can use a property to store all items (you can store in a different place as well) and use this object to store your keys by referencing the to a desired value on your collection.
You may need to implement the deletion logic to maintain the consistence between the collection and the dictionary.
Your factory would look like this:
.factory('StorageService', function($localStorage) {
$localStorage = $localStorage.$default({
things: {
items: []
}
});
var _getAll = function() {
return $localStorage.things.items;
};
var _add = function(thing) {
$localStorage.things.items.push(thing);
}
var _addByKey = function(thing, value) {
var i = $localStorage.things.items.push(value) - 1;
$localStorage.things[thing] = $localStorage.things.items[i];
}
return {
getAll: _getAll,
add: _add,
addByKey: _addByKey
};
})

string.Format in JS

I'm trying to simulate the C# string.Format() in JS.
For this, I have an object called string and a function called Format() passing as parameter, in a variadic function, a string with its placeholders and also its values.
An example should be:
string.Format("{0} - {1}", "Hello", "World");
that must return me Hello - World.
Although, it gives me just "{undefined} - {undefined}". I'm using global modifier to get all, but it doesn't works.
var string = {
Format: function() {
var text = arguments[0];
for (i = 1; i < arguments.length; i++) {
var result = text.replace(/([0-9]+)/g, arguments["$1"]);
}
console.log(result);
}
}
Where is my error?
You're always starting from the initial string (ignoring the previous replacements) and there are parts of you're function where it's unclear how it's supposed to work.
Here's a working implementation based on your general idea :
var string = {
Format: function() {
var args = arguments,
result = args[0].replace(/([0-9]+)/g, function(s) { return args[+s+1] });
console.log(result);
return result;
}
}
It logs "{Hello} - {World}"
Now, supposing you don't want to keep the braces and you also want to ensure you only replace numbers between braces, you can do this (without the debug logging) :
var string = {
Format: function() {
var args = arguments;
return args[0].replace(/{([0-9]+)}/g, function(s) {
return args[+s.slice(1,-1)+1]
});
}
}
It returns "Hello - World"

How to call a function on string jQuery

I was reading through fluent api I got a doubt.
I want to take in a string upon which a jQuery function or example is called upon
Function
function compareThis(newString) {
function compare(newString) {
if (this == newString) {
alert("same string");
} else {
alert("differnt string");
}
}
}
Where it is called as
("alerting").compareThis("alerted").compare(); //alert 'different string'
I want to pass the data/string not as parameter but as called upon.
JSFiddle
Note: I would like to call the function in similar cases like finding date interval etc
You can use prototype to add function to String class:
String.prototype.compare = function(newString){
if (this == newString) {
alert("same string");
} else {
alert("differnt string");
}
};
I think you should adapt the code for your function, but it's the idea.
Maybe I missed interpreted however, it looks as it you required a form of method chaining to compare string. To do this you can create a variable and create functions inside it.
var compare = (function(){
var thisString;
var stringToCompare;
var create = function(sVal) {
thisString = sVal;
return this;
};
// Public
var compareThis = function(sVal) {
stringToCompare = sVal;
return this;
};
var compare = function(anotherString) {
return thisString == stringToCompare;
};
return {
create: create,
compareThis: compareThis,
compare: compare
};
}());
var b = compare.create('test').compareThis('test').compare();
alert(b);
Example fiddle

Serializing a custom object which has methods. Methods being dropped after serialization - what steps to take?

I have created a custom object similar to this simplified example. My implementation gives Playlist more complex methods:
function Playlist(id) {
var _songs = [];
if(!id)
id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); });
var playlist = {
id: id,
title: "New Playlist",
clear: function(){
_songs = [];
_save();
},
songCount: function () {
return _songs.length;
},
getSongs: function () {
return _songs;
}
}
return playlist;
}
Now, I have another object, Playlists, which saves Playlist objects:
function playlists(){
var _playlists = null;
var _currentPlaylist = null;
var _save = function () {
localStorage.setItem('playlists', JSON.stringify(_playlists));
};
var _loadPlaylists = function(){
_playlists = localStorage.getItem('playlists');
try {
if (_playlists && _playlists != 'undefined')
_playlists = JSON.parse(_playlists);
}
catch(exception){
console.error(exception);
}
if(!_playlists){
_playlists = new Array();
var defaultPlaylist = new Playlist(null, null);
_playlists.push(defaultPlaylist);
_save();
}
};
var playlists = {
count: function(){
return _playlists.length;
},
getPlaylists: function(){
return _playlists;
},
getCurrentPlaylist: function(){
currentPlaylist = _currentPlaylist;
if(!currentPlaylist){
_loadPlaylists();
currentPlaylist = _playlists[0];
currentPlaylist.selected = true;
}
return currentPlaylist;
},
addPlaylist: function(playlistName){
var playlist = new Playlist(null, playlistName);
_playlists.push(playlist);
_save();
}
}
return playlists;
}
When I convert a playlist object from JSON to an object using JSON.parse I note that the Playlist object has been stripped of its methods. I believe this is because JSON.stringify does not know how to (or it does not know that it should) convert the object into JSON.
I was wondering what the proper response to this is? Is it possible to tag the methods as serializable? Or is more work required?
JSON.stringify() saves data properties, not methods. That's how it works.
If you're expecting it to save your actual javascript code, that is simply not how it's designed. If you wanted, you could add a data property that was the custom type of the object and when you read back in the object, you could use that to reattach the appropriate methods. But, that does not happen with JSON.stringify() and JSON.parse().
If you know in advance what type of object you're reading, you can create that type of object and pass it the saved JSON as an initializer.
As mentioned, stringify is designed to serialize properties, not function.
I found this blog post that goes through the process of explaining why this is the case, and finally how to preserve an object's functions through the use of the __proto__ property. Looks like the only way around it for now.

Categories