Adding my function into another? - javascript

I've added the first function superscriptDesignation to this code and now want to call it on the items in teamDesignations. Doing
return superscriptDesignation(teamDesignations);
gives me an error in the console that .replace is not defined. How can I add my function superscriptDesignation to the teamDesignations?
JS
var superscriptDesignation = function(designation) {
return designation.replace(/(®)/ig, "<sup>®</sup>").replace(/(™)/ig, "<sup> ™</sup>");
};
var getTeamDesignations = function(profile) {
//Designations for a single team member
var teamDesignations = [];
if (profile.team_members) {
teamDesignations = _.chain(profile.team_members)
.filter(_.compose(_.isArray, _.property('team_member_designations')))
.map(_.property('team_member_designations'))
.flatten()
.uniq()
.value();
}
return teamDesignations;
};

What this makes me think is that teamDesignations is not a string when it's being passed to superScriptDesignations. .replace() is only a method on the String prototype.
I'm not familiar with .uniq() and .flatten(), but is the result of that method chain a string? Either way, it's all in an if statement, so if that is not met teamDesignations could be an empty array when it's passed to superScriptDesignation.
You can either modify the replace() method in the first function to handle arrays, or put in some error handling to ensure that the parameter is a string. i.e:
var superscriptDesignation = function(designation) {
if(typeof(designation === 'string)) {
//... do your stuff
}
};

Related

How to assign existing function to object (not call it immediately) by it's name as a String from JSON file?

I would like some help assigning function to object. I have JSON file containing function names (as string ofc...) and in my code I have already existing functions. I don't want this functions to be called just assigned so I can call them later.
I also want to be able to pass a custom function as a string from JSON file. I tried to parse it but I get Unexpected token m...
operations.push --> run: is where I want to assign function.
This is my code with what I have tried so far:
async function operate(schemaObject) {
let operations = [];
for (let operation in schemaObject.operate) {
if(schemaObject.operate.hasOwnProperty(operation)) {
//Function name as a string ex: "matchIntegerOrUnlimited"
let functionName = schemaObject.operate[operation].action;
//Function parameter (val) ex: "test 123"
let functionParam = schemaObject.operate[operation].parameter;
//Custom Function ex: "return alert(Hello)
if (operation.custom) {
operations.push({
run: new Function("test 123", return alert("123"),
on: schemaObject.operate[operation].key
});
} else {
//Push existing Function matchIntegerOrUnlimited()
operations.push({
run: functionName, //"matchIntegerOrUnlimited"
on: schemaObject.operate[operation].key
});
}
}
}
console.log(operations);
return operations;
}
function matchIntegerOrUnlimited(val) {
if (contains(val, unlimitedPattern)) {
return 10000;
} else {
let number = val.match(numberPattern)[0];
return parseInt(number, 10);
}
}
So I expect to be able to just assign function that can be called later by giving a existing function name as Sting... and also if possible to give a custom function as a String

Pass a javascript function as part of a JSON [duplicate]

I've been looking around for a way to do this but can't seem to find anything, I have different configuration objects that I need to save as a text in variables for some processing later on, here is a sample:
object:
args.config.config = {
next: null,
final:[],
delimiter: '~', header: false,
step: function (row) {
var item = {
'line_code': row.data[0][0],
'order': row.data[0][1]
}
args.config.config.final.push(item);
},
complete: function (result) {
console.log('Reading data completed. Processing.');
return args.config.config.next(null, args.config.config.final);
},
error: function () {
console.log('There was an error parsing');
}'
}
I need to save this as a string, so something like:
args.config.config = "{object goes here}";
Without putting everything on one giant line or adding break line characters as this will be parsed later to be used in a config, and that will mess things up, any ideas?
UPDATE:
So changing them into text may not be the best solution, these configs will be stored in a mongo database, so it may take them as is (I have not tried it yet).
One of the other problems I was running into was that in the config object I had this:
final.push(item)
and
return next(null, final)
Which will be defined in another file using the config object:
other file:
exports.parse = function(args, next){//next is what I need to call in the config
var final = []; //this is the final referred to in the config object
....
Baby.parse(data, args.config)
}
So the return next(null, final) and final.push(result) have to refer the the var / function in the new file, but I have no idea how to get that to work, that't why I had to add a final array in the config object and a null next function, then assign it like so:
exports.parse = function(args, next){
args.config.next = next;
....
Baby.parse(data, args.config)
}
the object was calling it with the ugly line:
return args.config.config.next(null, args.config.config.final);
If anyone has a way around this, it would be much appreciated.
If you use JSON.stringify with a "replacer" function and
JSON.parse with a "reviver" function along with new Function(), you can do it:
I'm not sure I'm following the second (updated) question you have. Once the object is parsed back into an object, why can't you just initialize the next and final properties to valid objects before calling any of the object's methods? You can even add tests into that method that checks for the existence of final and next before returning anything.
var myObj = {
next: null,
final:[],
delimiter: '~',
header: false,
step: function (row) {
var item = {
'line_code': row.data[0][0],
'order': row.data[0][1]
};
args.config.config.final.push(item);
},
complete: function (result) {
console.log('Reading data completed. Processing.');
return args.config.config.next(null, args.config.config.final);
},
error: function () {
console.log('There was an error parsing');
}
};
// Stringify the object using a replacer function that will explicitly
// turn functions into strings
var myObjString = JSON.stringify(myObj, function(key, val) {
return (typeof val === 'function') ? '' + val : val;
});
// Now, parse back into an object with a reviver function to
// test for function values and create new functions from them:
var obj = JSON.parse(myObjString, function(key, val){
// Make sure the current value is not null (is a string)
// and that the first characters are "function"
if(typeof val === "string" && val.indexOf('function') === 0){
// Isolate the argument names list
var start = val.indexOf("(") + 1;
var end = val.indexOf(")");
var argListString = val.substring(start,end).split(",");
// Isolate the body of the function
var body = val.substr(val.indexOf("{"), val.length - end + 1);
// Construct a new function using the argument names and body
// stored in the string:
return new Function(argListString, body);
} else {
// Non-function property, just return the value
return val;
}
}
);
// Test the method:
obj.error(); // 'There was an error parsing' is written to console.
// Examine the object:
console.log(obj);

Javascript Array.prototype.filter() not working

I have this piece of code running on the client that filters a list of events:
if (res)
{
eventList.filter(function(event) {
const out = res.find(function(visibility) { return visibility.ID == event.id; }) == undefined;
return out;
});
alert(eventList);
}
displayEvents(eventList);
The problem is that even when out is false the element is not filtered out.
Just for debug I tried to return false in any case and the resulting array still had all the initial elements:
eventList.filter(function(event) {
return out;
});
What am I doing wrong here??
EDIT:
res is an array of JSON objects (containg only ID field) returned by the server, while eventList is a list of Facebook events, passed to this callback function from a Facebook API request
Array.prototype.filter does not change array inplace, it returns new array made of items that satisfies the provided predicate. It should look like this
var result = eventList.filter(function(event) {
return res.find(function(visibility) { return visibility.ID == event.id; }) === undefined;
});
You don't need to declare and assign variable and then return it from function, you can simply return expression

Create object with function parameters

How can i create object with function parameters?
function hell(par1, par2) {
return { par1 : par2 };
}
hell(ID, 1);
I want return { ID : 1 }
In modern JavaScript:
function hell(par1, par2) {
return { [par1] : par2 };
}
hell("ID", 1);
The brackets ([ ]) around the property name means that the name should be the value of the enclosed expression.
Note also that when you call the function, the value of the first argument should be a string. I changed your code to use "ID" instead of just ID; if you have a variable floating around named ID, of course, that'd be fine, so long as it can evaluate to a string.
This is a fairly recent addition to the language. If your code should run in old browsers, you'd have to do something like this:
function hell(par1, par2) {
var obj = {};
obj[par1] = par2;
return obj;
}

Understanding js return type

I have a function called which is returning ref to object literal nameObj. I want to access methods in the returned object but I am getting js error. why is setNameObj method not available on nameObj object?
var nameObj=function(){
var _locname;
return {
item:'item1',
getNameObj: function(){
return _locname
},
setNameObj: function(nm){
_locname = nm
}
}
}
console.log(nameObj.setNameObj('tempValue'));
console.log(nameObj.getNameObj());
Because nameObj is a function that returns an object that will have your methods!
Try calling it and then calling functions on the result:
console.log(nameObj().setNameObj('tempValue'));
console.log(nameObj().getNameObj());
Of course in this case it's largely moot, because each call will create a new closure. You most probably want one variable (or just convert nameObj to an IIFE).
var obj = nameObj();
obj.setNameObj('tempValue');
console.log(obj.getNameObj());
Because you're setting nameObj to be the function and not the result of that function. It looks like you want an IIFE here, so just add parentheses at the end of your function expression:
var nameObj=function(){
var _locname;
return {
item:'item1',
getNameObj: function(){
return _locname
},
setNameObj: function(nm){
_locname = nm
}
}
}();
console.log(nameObj.setNameObj('tempValue'));
console.log(nameObj.getNameObj());
Since nameObj is a function, you have to put the brackets after them to evaluate:
nameObj()
What you probably want is this:
var nameObj= (function(){
var _locname;
return {
item:'item1',
getNameObj: function(){
return _locname
},
setNameObj: function(nm){
_locname = nm
}
}
})();
console.log(nameObj.setNameObj('tempValue'));
console.log(nameObj.getNameObj());
Note the added parentheses (two sets) around the nameObj definition. There's a notable difference between getting a function, and getting the result of a function.

Categories