Parse cloud code - issues with promises - javascript

Here is my code
Parse.Cloud.define('filters', function(request, response){
var _ = require('underscore');
var customerGeoPoint = request.params.geolocation;
var rating = request.params.rating
var finalList = [];
// var arr = [];
var promises = [];
var query = new Parse.Query('ServiceProvider');
query.withinMiles("geoLocation", customerGeoPoint, 10);
query.find().then(function(spobjs){
return spobjs
}).then(function(newval){
var query2 = new Parse.Query('Customer');
for(i in newval){
query2.withinMiles('geoLocation', newval[i].get('geoLocation'), newval[i].get('serviceRadius'));
var sp = query2.first()
if(sp != null)
{
finalList.push(newval[i]);
}
}
return finalList ;
}).then(function(resval){
var arr = [];
var arr = _.sortBy(resval,'averageRating'); ** This Line doesn't work **
console.log(arr[0]);
return arr ;
}).then(function(checkval){
response.success(checkval);
},function(error){
// console.log(error);
response.error(error);
});
});
In the above code the line which reads "This Line doesn't work" does nothing. I have required underscore.js but still it doesn't sort the array. finalList value gets returned to the then promise after but it doesn't sort it and returns the same value as finalList. Can someone tell me what's the issue with this code?

When sorting parse objects with underscorejs, the iteratee must return the value of the attribute using get()...
var arr = _.sortBy(resval, function(o) { return o.get('averageRating'); });

Related

Javascript read from file

This nodejs file is suppose to read a file line by line. Each line represents and object that I create and add to an array. After finished reading the file it should return that array. Not an expert on javascript but this seems to return an empty array each time. I thought it had something to do with global but creating a temp array and pushing to it in parseline() didn't work either. What am I doing wrong?
var exports = module.exports = {};
const lineReader = require('line-reader');
const Obj = require("./Data")
const Data = Obj.Data;
var records = [];
exports.readAllLines = async function() {
await lineReader.eachLine('./datafile.dat', function(line) {
parseLine(line);
});
return records;
}
function parseLine(inputLine) {
var splitArray = inputLine.split("\t");
var date = new Date(Date.parse(splitArray[0]));
var o= splitArray[1];
var h= splitArray[2];
var l= splitArray[3];
var c= splitArray[4];
var v= splitArray[5];
var dataObject = new Data (date, o, h, l, c, v);
records.push(dataObject);
}
Calling Code
var readFiles = require("./ReadFile.js");
readFiles.readAllLines().then(function(result) {
console.log(result);
});
A simple solution using native apis
var fs = require('fs');
let fileArray = fs.readFileSync(filepath).split('\n');
As per line-reader docs
eachLine and open are compatible with promisify from bluebird
So in order to wait for each line to finish then return data you can install bluebird as per the example and change your code to be like the below
var exports = module.exports = {};
const lineReader = require('line-reader');
const Obj = require("./Data")
const Data = Obj.Data;
Promise = require('bluebird');
var eachLine = Promise.promisify(lineReader.eachLine);
var records = [];
exports.readAllLines = async function() {
await eachLine('./datafile.dat', function (line) {
parseLine(line);
});
return records;
}
function parseLine(inputLine) {
var splitArray = inputLine.split("\t");
var date = new Date(Date.parse(splitArray[0]));
var o= splitArray[1];
var h= splitArray[2];
var l= splitArray[3];
var c= splitArray[4];
var v= splitArray[5];
var dataObject = new Data (date, o, h, l, c, v);
records.push(dataObject);
}
Thanks to jfriends00 and others this is what I came up with. It was indeed a race condition where the array was being returned before the file was read.
var exports = module.exports = {};
const fs = require('fs');
const readline = require('readline');
const Obj = require("./Data")
const Data = Obj.Data;
exports.readAllLines = async function processLineByLine() {
var records = [];
const fileStream = fs.createReadStream('./datafile.dat');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
for await (const line of rl) {
records.push(parseLine(line));
}
return records;
}
function parseLine(inputLine, records) {
var splitArray = inputLine.split("\t");
var date = new Date(Date.parse(splitArray[0]));
var o= splitArray[1];
var h= splitArray[2];
var l= splitArray[3];
var c= splitArray[4];
var v= splitArray[5];
return new Data(date, o, h, l, c, v);
}
Calling Code
var readFiles = require("./ReadFile.js");
readFiles.readAllLines().then(result => {
console.log(result);
}).catch(exception => {
console.log(exception);
});

Generic code for Arrays

I want to create one loop that will access and push data from three arrays in JavaScript:
var tempArray1=new Array();
var tempArray2=new Array();
var tempArray3=new Array();
I tried following code:
for(var j=1; j<4; j++) {
var res = new Array();
var str = 'tempArray' + j;
res = str.split(" ");
}
but with this nothing happened.
Please help me to create generic code.
Brief
var res=[...tempArray1,...tempArray2,...tempArray3]
or more dynamic
var res=eval('[...tempArray1,...tempArray2,...tempArray3]') // since it is generic
DEMO :
var tempArray1=["I","love","JS"],tempArray2=["But","I'm"],tempArray3=["a crazy","JS","Programmer"]
function range(size){ /* for you case ,it returns : [1,2,3] */
return Array.from({length:size},(v,k)=>k+1)
}
function generate(size){
return eval('[...'+range(size).map((i)=>'tempArray'+i).join(',...')+']')
}
console.log(
generate(3)
)
var tempArray1 =[1,2,3];
var tempArray2 =[4,5];
var tempArray3 =[6];
function myConcat(){//This is the generic method
var result =[];
for (var i = 0; i < arguments.length; i++) {
result = result.concat(arguments[i]);
}
return result;
};
var conctenatedArray = myConcat(tempArray1,tempArray2,tempArray3);
console.log(conctenatedArray);
https://jsfiddle.net/8jwyzn0x/
**
OR
**
It would be good, if you wrap those array in a container object.
function myConcat(container){//This is the generic method
var result =[];
for(var i in container){
result = result.concat(container[i]);
}
return result;
};
var arrayContainer ={};
arrayContainer.tempArray1 =[1,2,3];
arrayContainer.tempArray2 =[4,5];
arrayContainer.tempArray3 =[6];
var conctenatedArray = myConcat(arrayContainer);
console.log(conctenatedArray);
https://jsfiddle.net/8jwyzn0x/1/

How return array of arrays in node js?

I have module like this in node js
var types = function (){
var typeList= new Array();
typeList[0] = "varchar";
var numericDTs= new Array();
numericDTs[0] = "tinyint";
var binaryDTs= new Array();
binaryDTs[0] = "tinyblob";
var data = array();
data[0] = typeList;
data[1] = numericDTs;
data[2] = binaryDTs;
return data;
}
module.exports = {
types: types,
}
i am calling this module like this
var types = require("./include/types");
console.log(types.types());
i got error like this
500 ReferenceError: array is not defined
no error if i return only types or typeList or binaryDTs.
How return array of arrays in node js?
Your error is here:
var data = array();
Write the following instead:
var date = [];
Actually replace every new Array() with [].
Instead of
var typeList= new Array();
typeList[0] = "varchar";
write var typeList = [ "varchar" ]; and so on.
EDIT:
Actually your whole function can be reduced to:
var types = function() {
return [ [ "varchar" ], [ "tinyint" ], [ "tinyblob" ] ];
};
Expanding on the other answer,
assuming you don't use the function anywhere else, you could just write
module.exports = {
types: function(){
return [["varchar"], ["tinyint"], ["tinyblob"]];
}
}

How to parse bracket tag on Javascript

I have tag like this, how the best way to get every key and value of those attribute and populate it within an array (number of attribute will be increasing)?
myData = '[data attr1="value1" attr2="value2" attr3="value3"]';
and get result array :
var arr = new Array();
arr['attr1'] = "value1";
arr['attr2'] = "value2";
arr['attr3'] = "value3";
and so on...
This probably does what you want, though it assumes that tag is already in the format you have described, i.e. a singular occurrence of [data ... ].
Also, the regular expression is purely based on what I've seen in your question; not sure whether it will break on other strings.
function decode(tag)
{
var r = /(\w+)="([^"]*)"/g,
h = {};
while ((m = r.exec(tag)) !== null) {
h[m[1]] = m[2];
}
return h;
}
Since you have string key in the data, use jquery object instead of array.
var arr = {};
var str = '[data attr1="value1" attr2="value2" attr3="value3"]​​​';
var n = str.split('[data ');
var str_arr = n[1].replace(']','').split(" ");
jQuery.each(str_arr,function(val){
var x = str_arr[val].split('=');
arr[x[0]] = x[1].replace('"','').slice(0,-1);
});
console.log(arr);
Try this code. It may help you.
Here is the DEMO
Though it can be more optimized if you put some more details about your code.
var tagRe = /\[(\w+)((?:\s+\w+="[^"]{0,50}")*)\s*]/g;
var attrRe = /\b(\w+)="([^"]*)"/g;
function parse(text) {
var result = [];
tagRe.lastIndex = 0; // reset start position
var tagMatch = tagRe.exec(text);
while (tagMatch) {
var currentTag = { 'name': tagMatch[1], 'attrs': {} };
var attrString = tagMatch[2];
attrRe.lastIndex = 0;
var attrMatch = attrRe.exec(attrString);
while (attrMatch) {
var attrName = attrMatch[1];
var attrValue = attrMatch[2];
currentTag.attrs[attrName] = attrValue;
attrMatch = attrRe.exec(attrString); // next match
}
result.push(currentTag);
tagMatch = tagRe.exec(text);
}
return result;
}
parse('[data attr1="value1" attr2="value2" attr3="value3"]');
> [{name:'data',attrs:{attr1:'value1',attr2:'value2',attr3:'value3'}}]
This works for any number of tags in the string. The name of the tag does not matter.

jquery map convert list of dashed properties into object

I would like to convert something like this (used in eg. in class):
var classname = "username_admin color_red strength_good"
into:
myvalues = {
username: 'admin',
color: 'red',
strength: 'good'
}
Here's at present my closest reach:
myvalues = $.map(classname.split(' '),function(el, i) {
var tmp = el.split('_');
var res = {};
res[tmp[0]] = tmp[1];
return res;
});
How to continue? http://jsfiddle.net/4EvWw/
I'd use each() like this because map() returns element of an array as stated in the docs:
jQuery.map( array, callback(elementOfArray, indexInArray) )
Returns: Array
Description: Translate all items in an array or object to new
array of items.
var classname = "username_admin color_red strength_good";
var res = {};
$.each(classname.split(' '),function(i, el) {
var tmp = el.split('_');
res[tmp[0]] = tmp[1];
});
console.log(res);
fiddle here http://jsfiddle.net/4EvWw/1/
You want to use .each rather than .map, and define res outside of the function:
var res = {};
$.each(classname.split(' '),function(i, el) {
var tmp = el.split('_');
res[tmp[0]] = tmp[1];
});
console.log(res);
http://jsfiddle.net/infernalbadger/4EvWw/3/
updated your code to the following http://jsfiddle.net/manuel/4EvWw/2/
var classname = "username_admin color_red strength_good";
var res = {};
$.map(classname.split(' '),function(el, i) {
var tmp = el.split('_');
res[tmp[0]] = tmp[1];
});
console.log(res);

Categories

Resources