Javascript function not returning false - javascript

This function is only returning true. I have added a console.log in the if block and it is called but the function doesn't return false.
function isUniform(List)
{
var ele = List[0];
List.forEach(function(item)
{
console.log(ele);
if(ele !== item)
{
return false;
}
})
return true;
}

You need another method for testing unifomity. Better use Array#every, which checks every value with the first item of the array and return true, if all elements are equal and false if not. The iteration stops with the first unequal element.
function isUniform(list) {
return list.every(function(item, _, array) {
return item === array[0];
});
}
The used Array#forEach returns always undefined:
forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

I think you can use this code;
function isUniform(List)
{
var res = true;
var ele = List[0];
List.forEach(function(item)
{
console.log(ele);
if(ele !== item)
{
res = false;
return;
}
})
return res;
}

Related

I keep getting "undefined" as an error, function not returning anything

I've been trying to figure out why I keep getting undefined, and I don't really see why, I know that I would get undefined if my function isn't returning anything, but in this case, even with returning in two places, I am still getting undefined. I think that the reason for that is that maybe I am not returning the value from innerFunc properly? I'm thinking maybe there's something wrong with my syntax here: innerFunc(arg) but I'm not sure how it is wrong, or what to change it to.
Any help would be appreciated.
Instructions:
Create a function "fastCache" that takes one argument (a function) and returns a function. When fastCache is invoked it creates an object that tracks calls to the returned function, where each input to the returned function is associated with its output. Every subsequent call to that returned function with the same argument will return the output directly from the object, instead of invoking the original function again.
function fastCache(func) {
const obj = {};
function innerFunc(arg) {
for (const key in obj) {
if (key === arg) {
return obj[arg]
} else {
obj[arg] = innerFunc(arg)
return innerFunc(arg)
console.log(obj[arg])
console.log(arg)
console.log(innerFunc(arg))
}
}
}
return innerFunc
// console.log(innerFunc(arg))
}
//example:
//SINGLE ARGUMENT CASE
const multiplyBy2 = num => num * 2;
const cachedMultiplyBy2 = fastCache(multiplyBy2);
If you want a simple cache function:
function cacheWrapper(fn) {
let cache = { };
return arg => {
if (cache.hasOwnProperty(arg)) {
return cache[arg];
}
return cache[arg] = fn(arg);
};
}
function test(x) {
return x * 2;
}
let testCached = cacheWrapper(test);
console.log(testCached(2));
console.log(testCached(2));
The key here is hasOwnProperty which will tell you if that cache slot is occupied or not. This avoids having to fumble around and find out the hard way with iteration.
If the number isn't already in the object, it won't be found in the loop.
function fastCache(func) {
const obj = {};
function innerFunc(arg) {
for (const key in obj) {
if (key === arg) {
return obj[arg]
}
}
obj[arg] = func(arg)
return func(arg)
}
return innerFunc
// console.log(innerFunc(arg))
}
//example:
//SINGLE ARGUMENT CASE
const multiplyBy2 = num => num * 2;
const cachedMultiplyBy2 = fastCache(multiplyBy2);
const result = cachedMultiplyBy2(8);

Undefined array parameter with Javascript

I can't see why this function is returning undefined:
function sumArray(array) {
array.reduce(function(result, item) {
return result + item;
})
}
array = [1,2,3]
sumArray(array)
I've tried something similar and it works ok (below), so I'm not sure if it's specific to the parameter being an array?
function sayNumber(num) {
return num + 1;
}
num = 1
sayNumber(num)
What you actually need is to add one more return statement.
function sumArray(array) {
//here
return array.reduce(function(result, item) {
return result + item;
});
}
array = [1,2,3];
sumArray(array);
//6
The function sumArray is not returning the result from array.reduce. Insert a return before your array.reduce.
It returns undefined because there is no return statement for the sumArray function.
(The anonymous function you pass to reduce has one, but that is a different function).
If you want to return the result of calling array.reduce when you have to say so explicitly:
return array.reduce(etc, etc…
You should return the value of the function sumArray
Like this:
function sumArray(array) {
return array.reduce(function(result, item) {
return result + item;
})
}

Get index in an array.filter callback function

I have the following array filter with a callback function:
array.filter(createPredicateFn(expression, comparator));
My call back function is declared as follow:
function createPredicateFn(expression, comparator) {
How can I get the index of the element inside my createPredicateFn?
Edit:
here is my predicate function:
function createPredicateFn(expression, comparator) {
var predicateFn;
if (comparator === true) {
comparator = angular.equals;
} else if (!angular.isFunction(comparator)) {
comparator = function (actual, expected) {
if (angular.isObject(actual) || angular.isObject(expected)) {
// Prevent an object to be considered equal to a string like `'[object'`
return false;
}
actual = angular.lowercase('' + actual);
expected = angular.lowercase('' + expected);
return actual.indexOf(expected) !== -1;
};
}
predicateFn = function (item) {
return deepCompare(item, expression, comparator);
};
}
Within your createPredicateFn() you have to return another function. This inner function can have up to three parameters:
the value of the element
the index of the element
the Array object being traversed
(Source: MDN)
Hence the second parameter of your inner function is the index you look for.
A simplistic example could look like this:
function createPredicateFn(expression, comparator) {
return function( val, index, arr ) {
// do something and return a boolean here
return index % 2 == 0;
}
}

Javascript function returning false even object found

I have a Product javascript array, which contains all the products information.
Created a function which iterate on this array and find the product by matching id.
var products = JSON.parse('[{"Product":{"id":"1","name":"My Product","description":"This is my new product","price":"10.00","currency":"$","stock":"0","image":"/image1.png"}},{"Product":{"id":"5","name":"Dummy Product 2","description":"Some dummy text goes here.","price":"10.00","currency":"$","stock":"100","image":"image2.jpg"}}]');
$(document).ready(function(){
console.log(products);
alert(findProduct(5)); //it will returns false everytime, evan it has matching product
});
function findProduct(product_id){
$.each(products, function(k, v){
if(v.Product.id == product_id){
console.log(v);
return products[k]; //or return 'v'
}
});
return false;
}
Check this Demo
Function returns false each time, even though it found the matching product id, don't know why? If I store the matching array key in a variable and after iteration, return the value of that key it returns proper object. But that's not proper way, cause I want to stop iteration and return the value if object found.
You are always returning false from findProduct, if the item is found you are returning from the $.each() callback method, but that is not reflected in the value returned by findProduct method.
function findProduct(product_id) {
var found = false;
$.each(products, function (k, v) {
if (v.Product.id == product_id) {
console.log(v);
found = products[k];
//return false to prevent further iteration
return false;
}
});
return found;
}
Use this instead:
function findProduct(product_id){
var result = false;
$.each(products, function(k, v){
if(v.Product.id == product_id){
console.log(v);
result = products[k]; //or return 'v'
return;
}
});
return result;
}
And here is the problem:
function findProduct(product_id){
$.each(products, function(k, v){
if(v.Product.id == product_id){
console.log(v);
return products[k]; //returns from the $.each callback
}
});
return false;
}
No need for jQuery's each function. Use libraries only when they are needed.
The problem is, that the 'each' method, is in fact ANOTHER function. Returning from it means nothing to the 'findProduct' function.
function findProduct(product_id){
for(var k in products){
var product = products[k];
if(product && product.Product && product.Product.id == product_id)
return product;
}
return false;
}

How to break out of a for loop inside a recursive function and return in Javascript?

I'm trying to compare keys of two objects, values of properties don't matter.
var obj1 = {
foo: {
abc: "foo.abc",
},
bar: {
aaa: {
bbb: "bar.aaa.bbb" // <-- difference
}
}
};
var obj2 = {
foo: {
abc: "foo.abc",
},
bar: {
aaa: {
ccc: "bar.aaa.ccc" // <-- difference
}
}
};
// function should return true if properties are identical, false otherwise
function compareObjProps(obj1, obj2) {
for(var prop in obj1) {
// when comparing bar.aaa.bbb and bar.aaa.ccc
// this does get logged, but the function doesn't return false
if(!obj2.hasOwnProperty(prop)) {
console.log("mismatch found");
return false;
}
if(typeof(obj1[prop]) === "object") {
compareObjProps(obj1[prop], obj2[prop]);
}
}
// this always returns
return true;
}
It seems that return false does not return from the top level function, but the recursive one.
So how can I return false when the whole matching function is done executing?
You're missing a return:
if(typeof(obj1[prop]) === "object"
&& !compareObjProps(obj1[prop], obj2[prop]))
{
return false;
}
Otherwise the result of recursive calls are going to be completely ignored.
Try this:
function compareObjProps(obj1, obj2) {
var result = true;
for (var prop in obj1) {
if (obj1.hasOwnProperty(prop) && !obj2.hasOwnProperty(prop)) {
console.log("mismatch found");
result = false;
} else if (typeof(obj1[prop]) === "object") {
result = compareObjProps(obj1[prop], obj2[prop]);
}
if (!result) {
break;
}
}
return result;
}
http://jsfiddle.net/gSYfy/4/
Yes, a function A called by function B cannot tell B to return. Some people have suggested returning the result of the recursive call, but that wouldn't give you the right result, as it would cause the program to return whether the first sub-object it found was identical, and not if all the objects are identical. I suggest you make this modification:
if(typeof(obj1[prop]) === "object") {
if(!compareObjProps(obj1[prop], obj2[prop])){
return false;
}
}
This will make your program propagate a "false" as you wanted, but make it keep going if the result was "true".

Categories