currying requests angularjs - javascript

I have three forms in the same container, all the actions use a objectId, so i wanna apply the objectId and send a function.
Obs: unfortunately i need to use ES5.
var doRequest = function(someId){
return function(reqFunction){
return reqFunction(someId);
};
};
var partial = doRequest("mongoId");
var getRequest = partial(function(){
});
var postRequest = partial(function(){
});
controllerAlias.getRequest = getRequest;
controllerAlias.postRequest = postRequest;

Curry is working, maybe is just missing one return function to do the proper assignations. Please check:
var doRequest = function(someId){
return function(reqFunction){
return reqFunction(someId);
};
};
var partial = doRequest("mongoId");
var getRequest = partial(function(id){
return function(){console.log('in getRequest: ' + id)};
});
var postRequest = partial(function(id){
return function(){console.log('in postRequest: ' + id)};
});
const controllerAlias = {};
controllerAlias.getRequest = getRequest;
controllerAlias.postRequest = postRequest;
controllerAlias.getRequest();
controllerAlias.postRequest();

Related

"Error: Expected a Resource or Concept." on the hyperledger composer playground

I am trying very hard to detect any problem in the following application. There is not any syntax error. However, executing the transaction gives the following error:
Error: Expected a Resource or Concept.
The script file is:
function secondSemesterReportCard(reportCard){
var factory = getFactory();
var NS = 'org.studentrecord.record';
var NS2 = 'org.studentrecord.reportcard'
return getAssetRegistry('org.studentrecord.record.Record').then(function(tempRecordRegistry){
return tempRecordRegistry.get(reportCard.studentDetails.registrationNumber);
}).then(function(tempRecord){
return tempRecord.secondSemesterReportId;
}).then(function(tempArray){
if(tempArray!= null && tempArray.lenght>0){
var ssReportCard = factory.newResource(NS2, 'SecondSemesterReportCard', reportCard.reportId );
var tempMarks = factory.newConcept(NS2, 'SecondSemesterMarks');
tempMarks.SubjectII = reportCard.SecondSemesterMarks.SubjectII;
tempMarks.SubjectIII = reportCard.SecondSemesterMarks.SubjectIII;
ssReportCard.secondSemesterMarks = tempMarks;
ssReportCard.result = reportCard.result;
var tempDetails = factory.newConcept(NS2, 'StudentDetails');
tempDetails.registrationNumber = reportCard.studentDetails.registrationNumber;
tempDetails.firstName = reportCard.studentDetails.firstName;
tempDetails.lastName = reportCard.studentDetails.lastName;
tempDetails.faculty = reportCard.studentDetails.faculty;
tempDetails.enrolledCollege = reportCard.studentDetails.enrolledCollege;
ssReportCard.studentDetails = tempDetails;
var tempRelationship = factory.newRelationship(NS,'Record',reportCard.studentDetails.registrationNumber);
ssReportCard.record = tempRelationship;
return ssReportCard;
}
}).then(function(ssReportCard){
var recordRegistry={};
return getAssetRegistry('org.studentrecord.reportcard.SecondSemesterReportCard').then(function(tempRecordRegistry){
return tempRecordRegistry.add(ssReportCard);
})
.then(function(){
return getAssetRegistry('org.studentrecord.record.Record');
})
.then(function(tempRecordRegistry){
recordRegistry = tempRecordRegistry;
return tempRecordRegistry.get(reportCard.studentDetails.registrationNumber);
}).then(function(tempRecord){
if(tempRecord.secondSemesterReportId){
tempRecord.secondSemesterReportId.push(reportCard.reportId);
}else{
var tempArray = [reportCard.reportId];
tempRecord.secondSemesterReportId = tempArray;
}
return recordRegistry.update(tempRecord);
});
});
}

Script work in a browser but not in NodeJS

I'm struggling trying to understand why this script works perfectly in the browser but not in Node.js in the server.
data = [{"stars": 3}, {"stars": 2}]
var ParseParameter = function(){
this.parser = "";
}
ParseParameter.prototype = {
setStrategy: function(parser) {
this.parser = parser;
},
parse: function(parameter) {
return this.parser.parse(parameter);
}
};
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
this.parse = function(parameter){
this.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[this.filter] == this.parameter;
}
}
var filter = 'stars',
parameter = '2',
parseParameter = new ParseParameter();
var integerParser = new IntegerParser(filter);
parseParameter.setStrategy(integerParser);
parseParameter.parse(parameter);
var dataFiltered = data.filter(parseParameter.parser.filterBy);
console.log(dataFiltered);
At the server, I print in console the values of this.parameter and this.filter at the function filterBy and these are undefined
I'm running on Node.js version 8.11.2
Any advice will be appreciated.
The is may be due to problem of this keyword in your script. Inside an inner function this refers to window or global object. For example,
Inside the following code, this.filter of this.filterBy is not referring to the filter property that exists inside the scope of IntegerParser function instead it is referring the variable being defined as var filter = 'stars'. Change this name to something else and you'll see undefined and it won't work on browser as well. That's what could be your issue.
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
this.parse = function(parameter){
this.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[this.filter] == this.parameter;
}
}
Instead of using this you could use a known solution for this problem by storing this to a variable for later usage. like in following example:
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
var self = this; // store this to self and use self in inner functions
this.parse = function(parameter){
self.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[self.filter] == self.parameter;
}
}
Your entire code including my solution is as follow:
data = [{"stars": 3}, {"stars": 2}]
var ParseParameter = function(){
this.parser = "";
}
ParseParameter.prototype = {
setStrategy: function(parser) {
this.parser = parser;
},
parse: function(parameter) {
return this.parser.parse(parameter);
}
};
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
var self = this;
this.parse = function(parameter){
self.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[self.filter] == self.parameter;
}
}
var filter = 'stars',
parameter = '2',
parseParameter = new ParseParameter();
var integerParser = new IntegerParser(filter);
parseParameter.setStrategy(integerParser);
parseParameter.parse(parameter);
var dataFiltered = data.filter(parseParameter.parser.filterBy);
console.log(dataFiltered);
It should work without any problem. Please try and see if it works for you.

Response not return full object after filter [Express.js]

I have in function like this:
var newConvs = [];
var tmp;
convs.filter(function (conv) {
tmp = conv;
conv = conv.conversation;
conv.reciver = tmp.reciver;
conv.conversationId = tmp._id;
newConvs.push(conv);
});
console.log(newConvs);
res.json({
message: newConvs
});
When I console.log(newConvs) it return full object, but in res.json... I don't get this 2: conv.reciver = tmp.reciver;
conv.conversationId = tmp._id;
Anyone know what is reason?

How to return array from JavaScript function that retrieves data from text file?

I am building a Windows 8 Store app with HTML/CSS/JavaScript. I am reading in data from a text file through a function, and then putting that data into an array. I am trying to return the array through the function, but it is not working. Any help would be greatly appreciated. I've attached my code snippet.
// Load user data
var DefineUserData = function LoadUserData() {
return Windows.Storage.ApplicationData.current.localFolder.getFileAsync(loadfile).done(function (UserFile) {
return Windows.Storage.FileIO.readTextAsync(UserFile).done(function (fileResult) {
var userdata = new Object();
var dataobject = {};
var innercount;
var outercount;
var fileResultByLines = fileResult.split("\n");
for (outercount = 0; outercount <= (fileResultByLines.length - 2) ; outercount++) {
var tempArray = fileResultByLines[outercount].split(",");
dataobject.metrictitle = tempArray[0];
dataobject.numinputs = tempArray[1];
dataobject.inputs = new Array();
for (innercount = 0; innercount <= parseInt(dataobject.numinputs) ; innercount++) {
dataobject.inputs[innercount] = tempArray[innercount + 2];
}
userdata[outercount] = dataobject;
}
return userdata;
});
},
function (errorResult) {
document.getElementById("resbutton1").innerText = errorResult;
})
}
Your DefineUserData function is returning a Promise, not a value. Additionally done functions don't return anything. Instead you'll need to use then functions instead of done functions in DefineUserData and then handle add a done function (or then) to the code that calls this function.
Also, You can make your promises easier to read, and easier to work with by chaining then functions instead of nesting them.
Currently on Win7 at the office so I can't test this, but try something similar to this pseudo-code. Note then functions instead of done. The last then returns your data. Sample snippet afterwards to illustrate calling this and handling the result.
// modified version of yours
var DefineUserData = function LoadUserData() {
return Windows.Storage.ApplicationData.current.localFolder
.getFileAsync(loadfile)
.then(function (UserFile) {
return Windows.Storage.FileIO.readTextAsync(UserFile);
}).then(function (fileResult) {
var userdata = new Object();
var dataobject = {};
var innercount;
var outercount;
var fileResultByLines = fileResult.split("\n");
for (outercount = 0; outercount <= (fileResultByLines.length - 2) ; outercount++) {
var tempArray = fileResultByLines[outercount].split(",");
dataobject.metrictitle = tempArray[0];
dataobject.numinputs = tempArray[1];
dataobject.inputs = new Array();
for (innercount = 0; innercount <= parseInt(dataobject.numinputs) ; innercount++) {
dataobject.inputs[innercount] = tempArray[innercount + 2];
}
userdata[outercount] = dataobject;
}
return userdata;
},
function (errorResult) {
document.getElementById("resbutton1").innerText = errorResult;
});
}
// some other code...
DefineUserData.done(function (userdata) {
// do something
});

How do get param from a url

As seen below I'm trying to get #currentpage to pass client params
Can someone help out thanks.
$(document).ready(function() {
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
}
var url = $("currentpage");
// yes I relize this is the part not working.
var client = jQuery.param("currentpage");
var page = jQuery.param("currentpage");
var devurl = "http://#/?clientsNumber=" + client + "&pageName=" + page ;
});
This is a method to extract the params from a url
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Here's how to use it in your code
var url = "?c=231171&p=home";
var params = getUrlParams(url);
var devurl = "http://site.com/?c=" + encodeURIComponent(params.c) + "&p=" + encodeURIComponent(params.p) + "&genphase2=true";
// devurl == "http://site.com/?c=231171&p=home&genphase2=true"
See it in action http://jsfiddle.net/mendesjuan/TCpsD/
Here's the code you posted with minimal changes to get it working, it also uses $.param as it's intended, that is to create a query string from a JS object, this works well since my suggested function returns an object from the url
$(document).ready(function() {
// This does not handle arrays because it's not part of the official specs
// PHP and some other server side languages support it but there's no official
// consensus
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
// no need for the extra load listener here, jquery.ready already puts
// your code in the onload
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
var url = $("currentpage");
var paramMap = getUrlParams(url);
// Add the genphase parameter to the param map
paramMap.genphase2 = true;
// Use jQuery.param to create the url to click on
var devurl = "http://site.com/?"+ jQuery.param(paramMap);
$('#mydev').click( function(){
window.open(devurl);
});
});

Categories

Resources