Write a higher-order function, checkConsistentOutput() - javascript

This function should have two parameters: a function and a value. It should call the argument function with the value two times. If the callback function produces the same result twice, it should return the result of the function call, otherwise, it should return the string 'This function returned inconsistent results'
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong :( ');
}
}
};
const addTwo = num => num + 2;
const timeFuncRuntime = funcParameter => {
let t1 = Date.now();
funcParameter();
let t2 = Date.now();
return t2 - t1;
};
// Write your code below
const time2p2 = timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTimes);
const checkConsistentOutput(func, val) => {
let checkOne = func(val);
let checkTwo = func(val);
if (checkOne === checkTwo){
return checkOne;
} else {
return 'This function returned inconsisent results'
}
}
I'm getting the error SyntaxError: Missing initializer in const declaration. please help me understand.

I'm seeing an error in the last const declaration that appears to be because it's missing an '='.
const checkConsistentOutput(func, val) => {
...
}
const checkConsistentOutput = (func, val) => {
...
}

Related

Array.prototype.filter() expects a value to be returned at the end of function array-callback-return

I am trying handle below code and its showing
enter image description here
const toArray = props =>
(props && props.split ? props.split(',') : props || []).map(item => item.trim());
const hasField = (entity, fields) => {
if (!fields.length) {
return false;
}
for (let i = 0; i < fields.length; i + 1) {
if (entity && entity.includes(fields[i])) {
return true;
}
}
return false;
};
module.exports = (entities, query) => {
const industries = toArray(query.industries);
const technologies = toArray(query.technologies);
const maturity = toArray(query.maturity);
return entities.filter(function (entity) {
const hasTecnology = hasField(entity.industries, industries);
const hasIndustury = hasField(entity.technologies, technologies);
const hasMaturity = hasField(entity.maturity, maturity);
const condition = hasTecnology || hasIndustury || hasMaturity;
if (condition) return entity;
}, []);
};
output showing:
23:26 error Array.prototype.filter() expects a value to be returned at the end of function
array-callback-return
Line 23:26 is ==> module.exports = (entities, query) => {
Could you please check this? What I wrongly doing here?
It's just as the error says - you're not always returning a value.
The callback return value only needs to be truthy or falsey. Change
if (condition) return entity;
to
return condition;

Calling a Javascript Function as a Primitive Datatype(Number in particular)

I am trying out some new implementations for a project in express and i have this issue:
code snippet:
let add_1 = () =>{
console.log(2)
}
let a = add_1();
let add_2 = () => {
console.log(5)
}
let z = add_2();
console.log(a +z);
upon running this code snippet i get a NaN
is there a way i can return the actual addition of these function calls (which in this case is 2+5=7) ?
you should use return statement instead of console.log like below
let add_1 = () =>{
return 2;
}
let a = add_1();
let add_2 = () => {
return 5;
}
let z = add_2();
console.log(a +z);
Your functions print to console but they do not return a value, so you cannot add them as numbers.
You can have each function do this return 5; or return 2; after the console.log(..) statement.
You can also user variables (instead of hard-coded values) or pass in parameters to the functions.
See below:
let add_1 = () => {
const val = 2;
console.log(val);
return val;
}
let a = add_1();
let add_2 = (val) => {
console.log(val);
return val;
}
let z = add_2(5);
console.log(a + z);
console.log(a + a);
console.log(z + z);

Please help me understand why one simple change breaks my compose/pipe function

This code works perfectly as intended:
function fn (result, func) {
return (...args) => func(result(...args))
}
function pipe(...funcs) {
let result = funcs[0]
for (let i = 1; i<funcs.length; i++) {
result = fn(result, funcs[i])
}
return result
}
For exapmle:
const reverser = pipe(
a => a.split(""),
b => b.reverse(),
c => c.join("")
)
console.log(reverser("FizzBuzz")) //logs out: zzuBzziF
But if I replace fn(result, funcs[i]) with (...args) => funcs[i](result(...args)) so it looks like this:
function pipe(...funcs) {
let result = funcs[0]
for (let i = 1; i<funcs.length; i++) {
result = (...args) => funcs[i](result(...args))
}
return result
}
Then I get InternalError: too much recursion
function pipe(...funcs) {
let result = funcs[0]
for (let i = 1; i<funcs.length; i++) {
result = (...args) => funcs[i](result(...args))
}
return result
}
const reverser = pipe(
a => a.split(""),
b => b.reverse(),
c => c.join("")
)
console.log(reverser("FizzBuzz")) //logs out: zzuBzziF
I feel like I'm missing something very obvious, but I just can't get why this is happening and have been struggling with this problem for hours.
You need to store the previous function; otherwise, result just keeps calling itself. The value of result is only evaluated inside the function when it is called, at which point it will already have been assigned another value.
function pipe(...funcs) {
let result = funcs[0]
for (let i = 1; i<funcs.length; i++) {
let prev = result;//stored previous function
result = (...args) => funcs[i](prev(...args))
}
return result
}
const reverser = pipe(
a => a.split(""),
b => b.reverse(),
c => c.join("")
)
console.log(reverser("FizzBuzz"))
You could also take a closure over it using an immediately-invoked function expression.
function pipe(...funcs) {
let result = funcs[0]
for (let i = 1; i<funcs.length; i++) {
result = ((result)=>(...args) => funcs[i](result(...args)))(result);
}
return result
}
const reverser = pipe(
a => a.split(""),
b => b.reverse(),
c => c.join("")
)
console.log(reverser("FizzBuzz"))

creating a spy function using javascript

I am trying to build a spy function that will do this.
const func1 = function (x, y) {return x + y};
const func2 = spy(func1);
func2(2, 5) // => 7
func2(4, 5) // => 9
func2.calls() // => 2
func2.args() // => [[2, 5], [4, 5]]
I have created this function but I can seem to get the calls and args
function spy(func) {
let count = 0;
let allArgs = [];
function ispy() {
let args2 = Array.prototype.slice.call(arguments);
spy.calls = function() {
return count++;
}
spy.args = function() {
return allArgs.push(args2)
}
func.apply(this, args2);
}
return spy;
}
const func1 = function (x, y) {return x + y};
const func2 = spy(func1);
console.log(func2(2, 5))
console.log(func2.calls())
console.log(func2.args())
Please help me fix it and let me know what am I missing?
A few things,
You need to keep track of count and allArgs for every invocation of the spy call.
You need to return the result of the spied upon function from spy.
function spy(func) {
let count = 0;
let allArgs = [];
function spy() {
// increment count on every invocation
count++;
let args2 = Array.prototype.slice.call(arguments);
// shove arguments onto the allArgs array.
allArgs.push(args2);
spy.calls = function() {
return count;
}
spy.args = function() {
return allArgs;
}
//return the result;
return func.apply(this, args2);
}
return spy;
}
const func1 = function (x, y) {return x + y};
const func2 = spy(func1);
console.log(func2(2, 5))
console.log(func2.calls())
console.log(func2.args())
You add functions to spy in a call of ispy() and increment count in call of calls instead of call of ispy, you don't return result of func, you assign calls and args functions in every call to ispy and many other mistakes
function spy(func) {
let count = 0;
let allArgs = [];
function ispy(...args) {
count++;
allArgs.push(args);
return func.apply(this, args);
}
ispy.calls = function() {
return count;
}
ispy.args = function() {
return allArgs;
}
return ispy;
}
const func1 = function (x, y) {return x + y};
const func2 = spy(func1);
console.log(func2(2, 5));
console.log(func2(4, 5));
console.log(func2.calls())
console.log(func2.args())
You could take the arguments directly with rest parameters and return in the function only the value of the variables. The assignemnt should happen outside of the function, because if not it would require a call of func2 first.
Each call of ispy should be counted and the arguments should be added to.
function spy(func) {
function ispy(...args) {
count++;
allArgs.push(args);
return func.apply(this, args);
}
let count = 0;
let allArgs = [];
ispy.calls = () => count;
ispy.args = () => allArgs;
return ispy;
}
const func1 = function (x, y) {return x + y};
const func2 = spy(func1);
console.log(func2.calls())
console.log(func2(2, 5))
console.log(func2.calls())
console.log(func2.args())

Promising gets stuck when doing actions on the data

I have a problem with promises. I have to do two queries to the database and I have to use then to read them. After that I have to merge them. What I did is as follows:
console.log("Start");
obj.find(query1).then(function(docs1) {
console.log("HERE0");
obj.find(query2).then(function(docs2) {
// Merge reports
console.log("HERE1");
console.log("docs1");
console.log("docs2");
c = [...docs1.files, ...docs2.files];
console.log("HERE2");
for (let i = 0; i < c.length; i++) {
for (let j = i + 1; j < c.length; j++) {
console.log("i = " + i + " j = " + j);
if(c[i].name == c[j].name) {
c[i].totals.invalid += c[j].totals.invalid ;
c[i].totals.valid += c[j].totals.valid ;
c[i].totals.total += c[j].totals.total;
c[i].totals.percentage = (c[i].totals.invalid / c[i].totals.valid) * 100;
c.splice(j, 1)
}
}
}
console.log("DONE");
response.send(c);
}, function (err) {
logger.error(err.message);
response.status(500).send(err.message);
});
}, function (err) {
logger.error(err.message);
response.status(500).send(err.message);
});
Output:
Start
HERE0
HERE1
<valid docs1>
<valid docs2>
After he gets to the line c = [...docs1.files, ...docs2.files]; it's get stuck (doesn't get to the next prints) and I don't understand why. I can see those docs being printed to the console.log but why it does not work on that line?
Also, is there a better way of of performing the find call so there will be one nesting instead of two (one .then)?
EDIT: the find method uses Q.defer();. Maybe I need to use it too?
You can use Promise.all with obj.find(query1) and obj.find(query2) expressions and later use them in thenable callback.
As far as merging function is concerned I prefer to use reduce and find for this example
Take a look at the snippet with mocked values.
const random = (from, to) => Math.floor(Math.random() * (to - from) + from);
const randomObj = (id) => {
const name = `sample ${id}`;
const invalid = random(1, 6);
const valid = random(6, 12);
const percentage = invalid / valid * 100;
return {
name,
totals: {
invalid,
valid,
percentage
}
}
}
const obj = {
find: (query) => Promise.resolve(Array(random(1, 4)).fill(0).map((pr, index) => randomObj(index + 1)))
}
const query1 = ""
const query2 = ""
Promise.all([obj.find(query1), obj.find(query2)]).then(results => {
let [list, secondList] = results;
console.log('first list', list);
console.log('second list', secondList);
const result = list.reduce((acc, record) => {
const item = secondList.find(pr => pr.name === record.name);
if (item) {
record.totals.invalid += item.totals.invalid;
record.totals.valid += item.totals.valid;
record.totals.percentage = record.totals.invalid / record.totals.valid * 100;
}
acc = [...acc, record];
return acc;
}, [...secondList.filter(pr => !list.some(npr => npr.name === pr.name))])
console.log('result', result);
})

Categories