I cant break my foreach with ajax inside - arrays

I have this:
var addresses_tmp = addresses.slice();
var final_addresses = [];
addresses.forEach(function (current_address, i) {
var near_addresses = [];
near_addresses.push(current_address);
addresses_tmp.forEach(function (next_address, j) {
if (current_address.address.info.code != next_address.address.info.code) {
var data = {
key : $scope.MicrosoftKey,
optmz : "distance",
routeAttributes : "routePath"
}
data["wp.0"] = current_address.address.location.lat + "," + current_address.address.location.lng;
data["wp.1"] = next_address.address.location.lat + "," + next_address.address.location.lng;
ajax.sendApiRequest(data, "GET", "http://dev.virtualearth.net/REST/V1/Routes/Driving", is_url=true).then(
function(response) {
var distance = response.data.resourceSets[0].resources[0].travelDistance;
if (distance < 0.020) {
near_addresses.push(next_address);
addresses_tmp.splice(j, 1);
}
if (j == addresses.length - 1) {
final_addresses.push(near_addresses);
if (near_addresses.length == 1) {
addresses_tmp.splice(j, 1);
}
addresses_tmp.splice(i, 1);
}
// if (count == addresses.length * addresses.length) {
// console.log("ya he acabado todasssss")
// }
},
function(error) {
console.log("error", error);
}
)
}
})
})
And I would like to break all function when the first foreach and the second foreach are finished but I cant put if condition to do this.
As I have ajax inside the second foreach, my variables are crazy so I cant put an if condition to break it.
I need to do this because I am compare two arrays and getting distance between two points (one in the first array and second in the other array)

Related

Execute methods sequence - React

I have written following code to get current user group Ids and later from that Ids I wanted to filter data from SharePoint list. First I want to execute
ServiceManager.getRemoteService().getCurrentUserGroups()
method. Once I get group Ids, I want to execute the next method. But unfortunately filter part of the REST query is blank because
this.groupIdString
is blank. This may be because both methods are executed same time. I'm new to React and I want to know is there any best approach to manage this scenario. Basically I want to execute the methods in the order I write.
public componentDidMount() {
this.groupIdString= "";
ServiceManager.getRemoteService().getCurrentUserGroups(this.props.siteUrl, "/_api/web/currentuser/groups").then((value) => {
if (value[0]) {
for (let i: number = 0; i < value.length; i++) {
if(value[i].Id != undefined){
this.groupIdString += "(UserGroupsId eq " + value[i].Id.toString()+")";
}
}
}
});
const restQuery = "/_api/Web/Lists/GetByTitle('Weather')/Items?$select=Title,NewsBody,UserGroupsId&$filter=("+this.groupIdString+")";
ServiceManager.getRemoteService().getWeatherListItems(this.props.siteUrl, restQuery).then((value) => {
if (value[0]) {
//code
}
});
}
#Sivakumar Piratheeban,
You can put the second request in the callback of the first call.
public componentDidMount() {
this.groupIdString = "";
ServiceManager.getRemoteService().getCurrentUserGroups(this.props.siteUrl, "/_api/web/currentuser/groups").then((value) => {
if (value[0]) {
for (let i: number = 0; i < value.length; i++) {
if (value[i].Id != undefined) {
this.groupIdString += "(UserGroupsId eq " + value[i].Id.toString() + ")";
}
}
// Second
const restQuery = "/_api/Web/Lists/GetByTitle('Weather')/Items?$select=Title,NewsBody,UserGroupsId&$filter=(" + this.groupIdString + ")";
ServiceManager.getRemoteService().getWeatherListItems(this.props.siteUrl, restQuery).then((value) => {
if (value[0]) {
//code
}
});
//
}
});
}
BR

Two for loops in one function will not save an array after exiting for loop

I have two arrays I need to compare in a test. I am testing a filter, it reads in an array of numbers and saves to spareArray. I then click on a filter button which is also the element the int list is listed in, style. I read in the list again and save it to the second array, spareIntArray. After the readin I send the arrays to two methods, one parses string to float and the second gets ride of '-' that are in my lists I do not want to compare. However after the run of the second for loop reading in spareIntArray the array is set to undefined. I tested that the array is filled with elements by doing a log and it seems to be. I am quite confused what is happening here.
/**
* Created by nphillips on 8/11/2015.
*/
var helper = require('./../pages/helper-page.js');
var capacityPage = module.exports = {
variables: {
//the theaterStyle element list
theaterStyle: element.all(by.css("[data-style='theater']")),
},
readsInTheater: function() {
capacityPage.readsIn(capacityPage.variables.theaterStyle);
},
removesDashes: function(style, array) {
while (array.indexOf('-') !== -1) {
array.splice(array.indexOf('-'), 1);
};
console.log(array + "count ");
return array;
},
readsIn: function(style) {
var spareArray = [];
var spareIntArray = [];
style.count().then(function(count) {
console.log(count);
j = 0;
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
style.get(i).getText().then(function(text) {
spareArray[j] = text;
console.log(text, spareArray[j], j);
expect(text).toEqual(spareArray[j++]);
});
}
}).then(function() {
// style.click()
browser.executeScript("arguments[0].scrollIntoView();", style.get(0).getWebElement());
style.count().then(function(count) {
console.log(count);
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
style.get(i).getText().then(function(text) {
spareIntArray[j] = text;
console.log(text, spareIntArray[j], j + "frawer");
expect(text).toEqual(spareIntArray[j++]);
});
};
});
spareArray = capacityPage.stringToFloatArray(spareArray);
spareIntArray = capacityPage.stringToFloatArray(spareIntArray);
capacityPage.removesDashes(style, spareArray);
capacityPage.removesDashes(style, spareIntArray);
expect(spareArray).toEqual(spareIntArray);
});
},
stringToFloatArray: function(array) {
function int_arr(a, b) {
return parseFloat(a) - parseFloat(b);
}
array = array.sort(int_arr);
console.log(array + "float");
return array;
},
};
Is spareIntArray being undefined?. It could be because you are calling stringToFloatArray on spareIntArray before it is filled. I think that your check should be inside the promise callback. However I am a bit concerned on why you are using asynchronous data retrieval on the document. Is there a way to do it in a synchronous way? Soemething like
style.count().then(function(count) {
console.log(count);
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
var text = style.get(i).getText();
spareArray.push(text);
console.log(text, spareArray[i], i);
expect(text).toEqual(spareArray[i]);
});
}
}).then(function() {
// style.click()
browser.executeScript("arguments[0].scrollIntoView();", style.get(0).getWebElement());
style.count().then(function(count) {
console.log(count);
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
var text = style.get(i);
spareIntArray.push(text);
console.log(text, spareIntArray[i], i + "frawer");
expect(text).toEqual(spareIntArray[i]);
};
spareArray = capacityPage.stringToFloatArray(spareArray);
spareIntArray = capacityPage.stringToFloatArray(spareIntArray);
capacityPage.removesDashes(style, spareArray);
capacityPage.removesDashes(style, spareIntArray);
expect(spareArray).toEqual(spareIntArray);
});
});
},

screeps.com: simple script not working, issue with bi-dimensional array

I get the following error from the console: "TypeError: Cannot read property '0' of undefined", it has something to do with the array but I cannot find the mistake.
module.exports =
{
create_creeps: function()
{
var aHarvester = [[TOUGH,TOUGH, MOVE, CARRY, WORK, MOVE]["harvester"]];
Spawn.prototype.createMyCreep = function(aCreep,sRole) {
if (!Game.spawns.Spawn1.spawning){
var nameCount = 0;
var name = null;
while(name == null)
{
nameCount++;
var tryName = sRole + nameCount;
if(Game.creeps[tryName] == undefined)
name = tryName;
}
var dbg= this.canCreateCreep(aCreep, name);
if(dbg == OK) {
console.log("Creating creep " + sRole);
return this.createCreep(aCreep , name,{ role:sRole });
} else {
console.log("error "+dbg+" "+sRole);
}
}
};
Game.spawns.Spawn1.createMyCreep(aHarvester[0],aHarvester[1][0]);
};
}
Please separate arrays with a comma
So
[[TOUGH,TOUGH, MOVE, CARRY, WORK, MOVE]["harvester"]]
Should be
[[TOUGH,TOUGH, MOVE, CARRY, WORK, MOVE],["harvester"]]

Name database child in Firebase?

This is the code I have.
function saveTrip()
{
routeData.clear();
for (var i = 0; i < dirDisplay.directions.routes[0].legs.length; i++) {
for (var j = 0; j < dirDisplay.directions.routes[0].legs[i].steps.length; j++) {
routeData.push(dirDisplay.directions.routes[0].legs[i].steps[j].path);
}
}
routeLinesRef.push(routeData, function(error){
if (error) {
$('#savedSpan').html('Data could not be saved.' + error);
} else {
$('#savedSpan').html('Data saved successfully!');
}
});
}
Array.prototype.clear = function() {
this.splice(0, this.length);
};
routeLinesRef.limit(10).on('child_added', function(snapshot)
{
// loop over each route we get from firebase
route = snapshot.val();
What function should be written to write into the hierarchy as shown in the image?
id = snapshot.name();
// make an array that is initially blank
// It will contain all the latitude and longitudes of each point on in the route
var routeCoordinates = [];
// This loops over each point on the route
for (var i=0; i<route.length; i++)
{
for (var j in route[i])
{
if (j==0 && i>0)
{
continue
}
else
{
This part just takes each point on the route, and converts it into
a google maps LatLng object. For example, if the data is [58.23, 18.8], it will do:
new google.maps.LatLng(58.23, 18.8) to it, which turns it into a format that google maps likes.
if (route[i][j].lb && route[i][j].mb) {
routeCoordinates.push(new google.maps.LatLng
(route[i][j].lb, route[i][j].mb));
//console.log(j + ' ' + snapshot.val()[route][i][j].lb, snapshot.val()[route][i][j].mb);
}
}
}
}
What should I do? I can't find any tutorial or anything.

ExtJS - null safe retrieval of complex objects using JsonReader

I am using a JsonReader to map Json data to variables to be used in a grid/form. The back end is in Java and there are complex objects which I Jsonify and pass to the ExtJS front end.
This is a part of my JsonReader which tries to retrieve a nested object -
{name:'status', type: 'string', mapping: 'status.name'}
This works fine when status has a value (not null in the server), but the grid load fails when status is null. Currently the work around I have is to send an empty object from the server in case of null, but I assume there should be a way to handle this in ExtJS. Please suggest a better solution on the ExtJS side.
I can think of two possibilities - one documented and one undocumented:
use the convert()-mechanism of Ext.data.Field:
{
name:'status',
mapping: 'status',
convert: function(status, data) {
if (!Ext.isEmpty(status) && status.name) {
return status.name;
} else {
return null;
}
}
}
The mapping property can also take an extractor function (this is undocumented so perhaps it may be a little bit risky to rely on this):
{
name:'status',
mapping: function(data) {
if (data.status && data.status.name) {
return data.status.name;
} else {
return null;
}
}
}
Use this safe json reader instead:
Ext.define('Ext.data.reader.SafeJson', {
extend: 'Ext.data.reader.Json',
alias : 'reader.safe',
/**
* #private
* Returns an accessor function for the given property string. Gives support for properties such as the following:
* 'someProperty'
* 'some.property'
* 'some["property"]'
* This is used by buildExtractors to create optimized extractor functions when casting raw data into model instances.
*/
createAccessor: function() {
var re = /[\[\.]/;
return function(expr) {
if (Ext.isEmpty(expr)) {
return Ext.emptyFn;
}
if (Ext.isFunction(expr)) {
return expr;
}
if (this.useSimpleAccessors !== true) {
var i = String(expr).search(re);
if (i >= 0) {
if (i > 0) { // Check all property chain for existence. Return null if any level does not exist.
var a = [];
var l = expr.split('.');
var r = '';
for (var w in l) {
r = r + '.' + l[w];
a.push('obj' + r);
}
var v = "(" + a.join(" && ") + ") ? obj." + expr + " : null";
return Ext.functionFactory('obj', 'return (' + v + ')');
} else {
return Ext.functionFactory('obj', 'return obj' + expr);
}
}
}
return function(obj) {
return obj[expr];
};
};
}()
});
I have changed Slava Nadvorny's example so that it completely works for ExtJS 4.1.1.
New extended class of Ext.data.reader.Json is below:
Ext.define('Ext.data.reader.SafeJson', {
extend: 'Ext.data.reader.Json',
alias : 'reader.safejson',
/**
* #private
* Returns an accessor function for the given property string. Gives support for properties such as the following:
* 'someProperty'
* 'some.property'
* 'some["property"]'
* This is used by buildExtractors to create optimized extractor functions when casting raw data into model instances.
*/
createAccessor: (function() {
var re = /[\[\.]/;
return function(expr) {
if (Ext.isEmpty(expr)) {
return Ext.emptyFn;
}
if (Ext.isFunction(expr)) {
return expr;
}
if (this.useSimpleAccessors !== true) {
var i = String(expr).search(re);
if (i >= 0) {
if (i > 0) { // Check all property chain for existence. Return null if any level does not exist.
var a = [];
var l = expr.split('.');
var r = '';
for (var w in l) {
r = r + '.' + l[w];
a.push('obj' + r);
}
var v = "(" + a.join(" && ") + ") ? obj." + expr + " : null";
return Ext.functionFactory('obj', 'return (' + v + ')');
} else {
return Ext.functionFactory('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
}
}
}
return function(obj) {
return obj[expr];
};
};
}()),
/**
* #private
* #method
* Returns an accessor expression for the passed Field. Gives support for properties such as the following:
*
* - 'someProperty'
* - 'some.property'
* - 'some["property"]'
*
* This is used by buildExtractors to create optimized on extractor function which converts raw data into model instances.
*/
createFieldAccessExpression: (function() {
var re = /[\[\.]/;
return function(field, fieldVarName, dataName) {
var me = this,
hasMap = (field.mapping !== null),
map = hasMap ? field.mapping : field.name,
result,
operatorSearch;
if (typeof map === 'function') {
result = fieldVarName + '.mapping(' + dataName + ', this)';
} else if (this.useSimpleAccessors === true || ((operatorSearch = String(map).search(re)) < 0)) {
if (!hasMap || isNaN(map)) {
// If we don't provide a mapping, we may have a field name that is numeric
map = '"' + map + '"';
}
result = dataName + "[" + map + "]";
} else {
if (operatorSearch > 0) {
var a = [];
var l = map.split('.');
var r = '';
for (var w in l) {
r = r + '.' + l[w];
a.push(dataName + r);
}
result = "("+a.join(" && ")+") ? "+dataName+"."+map+" : null";
} else {
result = dataName + map;
}
}
return result;
};
}())
});
So you can successfully processing nested JSON-data with null nodes.
Example of JSON:
{
root: [{
id: 1,
name: {
name: "John",
phone: "123"
},
},
{
id: 4,
name: null,
},
]
}
Working example with test data you can find here:
http://jsfiddle.net/8Ftag/

Resources