$.when apply for single request - javascript

I am trying to use $.when apply in my code. However, it seems that the format return is different for single and multiple request. How can i cater for it?? I am trying not to have another if else outside of it.
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});
This is what i do not want to do.
if (apiRequestList.length === 1) {
$.ajax({
});
} else {
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});
}

You can simply convert arguments into an array, when the length of apiRequestList is 1:
$.when.apply(null, apiRequestList).then(function() {
var _arguments = Array.prototype.slice.call(arguments);
if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
_arguments = [arguments];
for (var i = 0; i < _arguments.length; i++) {
var value = _arguments[i][0];
console.log(value);
}
});
Live Example on jsFiddle (since we can't do ajax on Stack Snippets):
function x(a) {
return $.post("/echo/html/", {
html: "a = " + a,
delay: Math.random()
});
}
function doIt(apiRequestList) {
$.when.apply(null, apiRequestList).then(function() {
var _arguments = arguments;
if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
_arguments = [arguments];
for (var i = 0; i < _arguments.length; i++) {
var value = _arguments[i][0];
console.log(value);
}
console.log("----");
});
}
doIt([x(1), x(2), x(3)]);
doIt([x(4)]);
Example output (it'll vary because of the Math.random()):
a = 4
----
a = 1
a = 2
a = 3
----

Related

Flatten Nested Array Without Using Flatten Function

I'm currently stuck on a problem. I'm trying to make [[1,2,[3]],4] -> [1,2,3,4] but cannot get it to work. The output I keep getting is: 1,2,3,4
1,2,3
3
3
3
3..........3
function flattenArray(input) {
var result = [];
console.log(input.toString());
for(i = 0; i < input.length; i++) {
if(input[i].constructor === Array) {
result.push(flattenArray(input[i]));
} else {
result.push(input[i]);
}
}
return result;
}
console.log(flattenArray([[1,2,[3]],4]));
I have this in my common.js file. I use it all the time.
Array.prototype.flatten = function () {
var ret = [];
for (var i = 0; i < this.length; i++) {
if (Array.isArray(this[i])) {
ret = ret.concat(this[i].flatten());
} else {
ret.push(this[i]);
}
}
return ret;
};
Here it is as a function:
function flattenArray(input) {
console.log(input.toString());
var ret = [];
for (var i = 0; i < input.length; i++) {
if (Array.isArray(input[i])) {
ret = ret.concat(flattenArray(input[i]));
} else {
ret.push(input[i]);
}
}
return ret;
}

How to use function outside $scope ( error: function isn't defined)

I have a rzslider which takes in true or false for disabled. I want disable to be true based on a function. So I want to make it disabled:$scope.truthy
I have a function called checkDupsName() checkDupsName should return true if there is a duplicate, false otherwise. I set my $scope.truthy variable to be true if the function returns true but the issue is, when I call it outside this function ( in my slider), it's ALWAYS false.
$scope.checkDupsName = function(Mylist) {
var i, j, n;
n = Mylist.length;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (Mylist[i] === Mylist[j]) {
return true;
}
}
}
return false;
};
$scope.truthy=false;
$scope.nameList = [];
var Types = [];
$scope.loadRuleList = function() {
PrioritizeService.getData($scope.prioritizeURL).
then(function(response) {
if (response) {
Types = response;
}
for (var k = 0; k < Types.length; k++) {
$scope.nameList.push(Types[k].name);
}
if($scope.checkDupsName($scope.nameList)) {
$scope.truthy=true;
}
};
$scope.slider = {
value: 1,
options: {
floor: 0,
ceil: 3,
showTicks: true,
showTicksValues: true,
disabled:$scope.truthy
}
};
You are defining it inside of your function that is being called by then. You should move it outside and make it a function defined/declared on the scope instead and have it take the data it uses as a parameter.
// initialize it so your code does not blow up in the case of forgotten undefined or null check
$scope.nameList = [];
$scope.loadRuleList = function() {
var me = this;
PrioritizeService.getData($scope.MyURL).
then(function(response) {
if (response) {
Types = response;
}
// re-init the nameList field
me.nameList = [];
for (var k = 0; k < Types.length; k++) {
me.nameList.push(Types[k].name)
}
//check for duplicates
var areDups = me.checkDupsName(me.nameList);
}
}
$scope.checkDupsName = function(listToCheck) {
var i, j, n;
n = listToCheck.length;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (listToCheck[i] === listToCheck[j]) {
return true;
}
}
}
return false;
}

Improvising Code Into A More DRY Approach?

I am formatting an array in the function inputCategories, and am unable to correctly add a third argument of "category" - forcing me replicate the function multiple times.
Here is the current state:
Calling the function with arguments.
$scope.categories = inputCategories($scope.item.categories, $scope.settings.categories);
function inputCategories (input, settings) {
var updatedSettings = [];
angular.forEach(input, function(obj) {
updatedSettings.push({"category": obj, "ticked": true});
});
var list = updatedSettings.concat(settings);
list.sort(function(a, b) {
return (a.category > b.category) - (a.category < b.category);
});
for ( var i = 1; i < list.length; i++ ){
if(list[i-1].category == list[i].category) {
list.splice(i,1);
}
}
return list;
};
Here are the places which would require a third argument of "category".
function inputCategories (input, settings) {
var updatedSettings = [];
angular.forEach(input, function(obj) {
updatedSettings.push({****"category"****: obj, "ticked": true});
});
var list = updatedSettings.concat(settings);
list.sort(function(a, b) {
return (a.****category**** > b.****category****) - (a.****category**** < b.****category****);
});
for ( var i = 1; i < list.length; i++ ){
if(list[i-1].****category**** == list[i].****category****) {
list.splice(i,1);
}
}
return list;
};
I think that the issue I am having is because I am mixing up strings and a variable that is a string, inside of the object on the fourth line...?
Perhaps you could do something like this:
function inputCategories (input, settings, category) {
var updatedSettings = [];
angular.forEach(input, function(obj) {
var setting = { "ticked": true };
setting[category] = obj;
updatedSettings.push(setting);
});
var list = updatedSettings.concat(settings);
list.sort(function(a, b) {
return (a[category] > b[category]) - (a[category] < b[category]);
});
for ( var i = 1; i < list.length; i++ ){
if(list[i-1][category] == list[i][category]) {
list.splice(i,1);
}
}
return list;
};

I can't figure out why it's saying that the matcher function is undefined.

This code is designed to identify an array of anagrams for a string given an array of possible anagrams.
var anagram = function(input) {
return input.toLowerCase();
}
I'm adding the matcher function here to the String prototype.
String.prototype.matcher = function(remainingLetters) {
var clone = this.split("");
for (var i = 0; i < clone.length; i++) {
if (clone[i].indexOf(remainingLetters) > -1) {
remainingLetters.splice(clone[i].indexOf(remainingLetters, 1));
clone.splice(i, 1);
}
}
if (remainingLetters.length == 0 && clone.length == 0) {
return true;
}
else {
return false;
}
}
a
String.prototype.matches = function(matchWordArray) {
var result = [];
for (var i = 0; matchWordArray.length; i++) {
var remainingLetters = this.split("");
if (matchWordArray[i].matcher(remainingLetters)) {
result.push(arrayToMatch[i]);
}
}
return result;
}
var a = anagram("test");
a.matches(["stet", "blah", "1"]);
module.exports = anagram;
Should probably be:
for (var i = 0; i < matchWordArray.length; i++) {
The original statement:
for (var i = 0; matchWordArray.length; i++) {
...would result in an infinite loop because matchWordArray.length is always truthy (3) in your test.

returning a value after for loops

So, I have been trying for the past few hours to get an result out of a function after performing some for loops :
Cluster.prototype.initiate_api_data_fetching = function(username) {
var self = this,
object = [];
return self.initiate_available_market_search(username, function(data_object){
var json_obj = JSON.parse(data_object);
for(var obj_key in json_obj) {
for (var i = json_obj[obj_key].length - 1; i >= 0; i--) {
self.initiate_market_items_data_fetching(username, json_obj[obj_key][i].site, function(data_obj){
var json_object = JSON.parse(data_obj);
for(var data_key in json_object) {
for (var j = json_object[data_key].length - 1; j >= 0; j--) {
object.push(json_object[data_key][j]);
/*log(object);*/
};
};
log(object);
});
};
};
});
};
Making abstraction of all the variables and other things that make no sense to you readers, I would just like to know how can I return the object array with the data that I\m pushing in it. Everything is fine if I\m logging where the /*log(object);*/ is, but if I want to see what the object contains at the end of the function, I get an empty array.
I suggest you add a callback to your main function and call it when done..
Cluster.prototype.initiate_api_data_fetching = function (username, callback) {
var self = this,
object = [];
return self.initiate_available_market_search(username, function (data_object) {
var json_obj = JSON.parse(data_object)
, counter = 0;
function done() {
counter -= 1;
if (counter === 0) {
callback(object);
}
}
for (var obj_key in json_obj) {
if (!json_obj.hasOwnProperty(obj_key)) { continue; }
for (var i = json_obj[obj_key].length - 1; i >= 0; i--) {
counter += 1;
self.initiate_market_items_data_fetching(username, json_obj[obj_key][i].site, function (data_obj) {
var json_object = JSON.parse(data_obj);
for (var data_key in json_object) {
if (!json_object.hasOwnProperty(data_key)) { continue; }
for (var j = json_object[data_key].length - 1; j >= 0; j--) {
object.push(json_object[data_key][j]);
/*log(object);*/
}
}
done();
});
}
}
});
};
PS. 1 assumption is that initiate_api_data_fetching is async.
PS. 2 Follow the advice from the commenters above to improve your code. I answered your immediate question by showing you how to synchronise async calls, but don't stop there.

Categories

Resources