I have:
function val(a,z){
return a/2, z+8;
}
val(3,4);
Put this result:
x = 1,5
y = 12
in a Array;
[x,y];
Thanks.
If you want to return multiple variables in an array then just add [] to your return statement.
function val(a,z){
return [a/2, z+8];
}
//then , the first array element is the x, second one is y
//var a = val(4,6)
//a[0] = 2 <- x
//a[1] = 14 <- y
Try to return as object
Like this
function val(a, z) {
return {
x: a / 2,
y: z + 8
};
}
var data = val(3, 4);
console.log(data.x);
console.log(data.y);
Related
Goal
I am at the final stage of scripting a Luhn algorithm.
Problem
Let's say I have a final calculation of 73
How can I round it up to the next 0? So the final value is 80.
And lastly, how can I get the value that made the addition? e.g. 7 is the final answer.
Current code
function validateCred(array) {
// Array to return the result of the algorithm
const algorithmValue = [];
// Create a [2, 1, 2] Pattern
const pattern = array.map((x, y) => {
return 2 - (y % 2);
});
// From given array, multiply each element by it's pattern
const multiplyByPattern = array.map((n, i) => {
return n * pattern[i];
});
// From the new array, split the numbers with length of 2 e.g. 12 and add them together e.g. 1 + 2 = 3
multiplyByPattern.forEach(el => {
// Check for lenght of 2
if(el.toString().length == 2) {
// Split the number
const splitNum = el.toString().split('');
// Add the 2 numbers together
const addSplitNum = splitNum.map(Number).reduce(add, 0);
// Function to add number together
function add(accumalator, a) {
return accumalator + a;
}
algorithmValue.push(addSplitNum);
}
// Check for lenght of 1
else if(el.toString().length == 1){
algorithmValue.push(el);
}
});
// Sum up the algorithmValue together
const additionOfAlgorithmValue = algorithmValue.reduce((a, b) => {
return a + b;
});
// Mod the final value by 10
if((additionOfAlgorithmValue % 10) == 0) {
return true;
}
else{
return false;
}
}
// Output is False
console.log(validateCred([2,7,6,9,1,4,8,3,0,4,0,5,9,9,8]));
Summary of the code above
The output should be True. This is because, I have given the total length of 15 digits in the array. Whereas it should be 16. I know the 16th value is 7, because the total value of the array given is 73, and rounding it up to the next 0 is 80, meaning the check digit is 7.
Question
How can I get the check number if given array length is less than 15?
You could do something like this:
let x = [73,81,92,101,423];
let y = x.map((v) => {
let remainder = v % 10;
let nextRounded = v + (10-remainder);
/* or you could use
let nextRounded = (parseInt(v/10)+1)*10;
*/
let amountToNextRounded = 10 - remainder;
return [nextRounded,amountToNextRounded];
});
console.log(y);
EDIT
As noticed by #pilchard you could find nextRounded using this more simplified way:
let nextRounded = v + (10-remainder);
https://stackoverflow.com/users/13762301/pilchard
I think what you need is this:
var oldNum = 73
var newNum = Math.ceil((oldNum+1) / 10) * 10;;
Then check the difference using this:
Math.abs(newNum - oldNum);
This question already has answers here:
Where argument of first next() call goes? [duplicate]
(2 answers)
Closed 6 years ago.
I was reading this article about javascript generators, and I reached the following snippet:
function *foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
return (x + y + z);
}
var it = foo( 5 );
// note: not sending anything into `next()` here
console.log( it.next() ); // { value:6, done:false }
console.log( it.next( 12 ) ); // { value:8, done:false }
console.log( it.next( 13 ) ); // { value:42, done:true }
I don't understand the purpose of the first it.next(). After executing it, this line, shouldn't the iterator be paused at var z = yield (y / 3), with y having the value of 6? Shouldn't it.next(12) supply the param for yield (y / 3), and z be 4 after this? I don't understand why the result of the function is not 5 + 12 + 4. It's somehow as if the first it.next() is ignored. Is this the case? Can someone please shed some light?
This may help
function *foo(x) {
var y = 2 * (yield (x + 1));
// x = 5 (from foo(5) ) so it yields 6
// next(12) => var y = 2 * (12) == 24
var z = yield (y / 3);
// from above y = 24 so yields 8
// next(13) => var z = 13
return (x + y + z);
// 5 + 24 + 13 == 42 (and done: true)
}
You might want to add some logging statements to see what is going on:
function *foo(x) {
console.log("starting");
var y = 2 * (yield (x + 1));
console.log("y", y);
var z = yield (y / 3);
console.log("z", z);
return (x + y + z);
}
var it = foo( 5 );
console.log("it", it);
console.log(it.next());
console.log(it.next(12));
console.log(it.next(13));
logs
it {next: …}
starting
{ value:6, done:false }
y 24
{ value:8, done:false }
z 13
{ value:42, done:true }
As you can see, calling foo(5) only creates the generator object, but does not yet start it. Only the first call to it.next() will do that, returning the result from the first yield. This first call does not take any argument, because it's not accessible inside the generator function anyway.
Only the second call to .next(12), here passing in a value, will then resume the generator code, with that passed-in value being the result of the yield expression (which is then multiplied by 2).
I want to be able to run the func n times with this createIterator function.
var createIterator = function (func, n) {
getDouble = function (x) {
return x + x;
};
return getDouble * n;
};
I want to be able to do this with the code:
var getQuad = createIterator(getDouble, 2);
getQuad(2) //8
Here are the tests is needs to pass:
Test.describe("Iterator for 'getDouble' function", function() {
var getDouble = function (n) {
return n + n;
};
Test.it("Running the iterator for once", function() {
var doubleIterator = createIterator(getDouble, 1);
Test.assertEquals(doubleIterator(3), 6, "Returns double of 3 as 6");
Test.assertEquals(doubleIterator(5), 10, "Returns double of 5 as 10");
});
Test.it("Running the iterator twice", function() {
var getQuadruple = createIterator(getDouble, 2);
Test.assertEquals(getQuadruple(2), 8, "Returns quadruple of 2 as 8");
Test.assertEquals(getQuadruple(5), 20, "Returns quadruple of 5 as 20");
});
});
I have been at this for awhile and have not been able to figure this out. Any help would be awesome. Thanks!
You can write a simple repeat procedure that when applied to n, f, and x, will repeat the application of function f to argument x, n times.
// ES6
const repeat = n => f => x =>
n === 1 ? f(x) : repeat(n-1)(f)(f(x));
const getDouble = x => x * 2;
const double = repeat(1)(getDouble);
const quad = repeat(2)(getDouble);
See it work
console.log(double(3)); // 6
console.log(double(5)); // 10
console.log(quad(2)); // 8
console.log(quad(5)); // 20
Let step through the evaluation of one of the examples:
const double = repeat(1)(getDouble);
Because repeat has been applied to n and f here, it returns
x => 1 === 1 ? getDouble(x) : repeat(0)(getDouble)(getDouble(x))
Now, when we call
double(3);
Substitute 3 for x
1 === 1 ? getDouble(3) : repeat(0)(getDouble)(getDouble(3));
Because 1 === 1, the first part of the ternary expression is returned
getDouble(3); // 6
Recap:
double(3) === getDouble(3) === 6
Now let's see the same process for quad
const quad = repeat(2)(getDouble);
Because repeat has been applied to n and f here, it returns
x => 2 === 1 ? getDouble(x) : repeat(1)(getDouble)(getDouble(x))
Now, when we call
quad(2);
Substitue 2 for x
2 === 1 ? getDouble(2) : repeat(1)(getDouble)(getDouble(2));
Because 2 === 1 is false, the second part of the ternary expression is returned
repeat(1)(getDouble)(getDouble(2))
repeat(1)(getDouble)(4)
So we have to call repeat again, with n=1, f=getDouble, x=4, so
1 === 1 ? getDouble(4) : repeat(0)(getDouble)(getDouble(4))
Because 1 === 1, the first part of the ternary expression is returned
getDouble(4); // 8
Recap:
quad(2) === getDouble(4) === 8
If you need the ES5, here you go
// ES5
var repeat = function repeat(n) {
return function (f) {
return function (x) {
return n === 1 ? f(x) : repeat(n - 1)(f)(f(x));
};
};
};
var getDouble = function getDouble(x) {
return x * 2;
};
var double = repeat(1)(getDouble);
var quad = repeat(2)(getDouble);
console.log(double(3)); // 6
console.log(double(5)); // 10
console.log(quad(2)); // 8
console.log(quad(5)); // 20
Lastly,
If you want your original API, which I believe to be inferior, we can still implement that
// ES6
const createIterator = (f, n) => x =>
n === 1 ? f(x) : createIterator(f, n-1)(f(x));
const getDouble = x => x * 2;
const double = createIterator(getDouble, 1);
const quad = createIterator(getDouble, 2);
And here's the ES5
// ES5
var createIterator = function createIterator(f, n) {
return function (x) {
return n === 1 ? f(x) : createIterator(f, n - 1)(f(x));
};
};
var getDouble = function getDouble(x) {
return x * 2;
};
var double = createIterator(getDouble, 1);
var quad = createIterator(getDouble, 2);
Both implementations work identically
So why is repeat(n)(f)(x) better ?
Well, because the function is fully curried, you can partially apply it in meaningful ways.
const getDouble = x => x * 2;
const once = repeat(1);
const twice = repeat(2);
const thrice = repeat(3);
const quad = twice(getDouble);
quad(5); // 20
const annoyingAlert = thrice(x => {alert(x); return x;});
annoyingAlert('wake up !'); // displays 'wake up !' three times
Your function isn't as flexible because it takes the function, f, and the number of times, n, as a tuple. Getting around this would require manually currying your function or using a Function.prototype.bind hack.
Try rearranging variables. Note, getDouble would be undefined at var getQuad = createIterator(getDouble, 2); as getDouble is defined within createIterator
var createIterator = function (func, n) {
getDouble = function (x) {
return (x + x) * n;
};
return func || getDouble;
};
var getQuad = createIterator(null, 2);
console.log(getQuad(2)) //8
alternatively
var createIterator = function(func, n) {
getDouble = function(x) {
return x + x;
};
return func.bind(null, n * n) || (getDouble(n)) * n;
};
var getQuad = createIterator(function(x) {
return x + x;
}, 2);
console.log(getQuad(2))
I just want to run getDouble n times.
You could use a loop inside of createIterator , return accumulated value as variable within function returned from createIterator that can be multiplied by parameter passed to getQuad
var createIterator = function(func, n) {
getDouble = function(x) {
return x + x;
};
var curr = n, res = 0;
while (--curr) {
res += func && func(n) || getDouble(n);
}
return function(y) {
return res * y
}
};
var getQuad = createIterator(null, 2);
console.log(getQuad(5)) // 20
You can do it like this,
Create an empty array of n
Fill the array by the function(arguments)
Join the array by operator
Create a function constructor using the joined array and arguments
Use the new function inside another function to pass the arguments from outside, and then return this new function.
Code snippet of what I am saying is here (if your browser supports Array.prototype.fill)
var createIterator = function (func, n, operator) {
operator = operator || "+";
var inner = Function(["f", "a"], "return " + Array(n ).fill("f(a)").join(operator) + ";");
return function (arg) {
return inner(func, arg);
};
};
var c = createIterator(function (n) {return n + n;}, 2);
document.write(c(3) + "<br/>");
document.write(c(6) + "<br/>");
var d = createIterator(function (n) {return n + n;}, 3, "+");
document.write(d(3) + "<br/>");
document.write(d(6) + "<br/>");
otherwise use this snippet
var createIterator = function (func, n, operator) {
operator = operator || "+";
var array = [];
for (var i = 0; i < n; i += 1) {array[i] = "f(a)";}
var inner = Function(["f", "a"], "return " + array.join(operator) + ";");
return function (arg) {
return inner(func, arg);
};
};
var c = createIterator(function (n) {return n + n;}, 2);
document.write(c(3) + "<br/>");
document.write(c(6) + "<br/>");
var d = createIterator(function (n) {return n + n;}, 3, "+");
document.write(d(3) + "<br/>");
document.write(d(6) + "<br/>");
I'm going through some tutorials and saw this block of code that I can't figure out. Can someone walk me through it please? I don't understand how the return ultimately executes the variable function.
var plus = function(x,y){ return x + y };
var minus = function(x,y){ return x - y };
var operations = {
'+': plus,
'-': minus
};
var calculate = function(x, y, operation){
return operations[operation](x, y);
}
calculate(38, 4, '+');
calculate(47, 3, '-');
operations is an object that has + and - as keys, so by passing one of those to it you will get
operations['+'] = plus
Now, the brackets indicate a function call which can also be made via a variable as in this case. So translated the return statement is nothing more than
return plus(x,y);
var calculate = function(x, y, operation){
return operations[operation](x, y); // operations['+'] = plus
}
Which calls above method and returns the value returned by that method.
Explanation
Look at my comments for an explanation.
var plus = function(x,y){ return x + y }; //-- var plus contains this function now.
var minus = function(x,y){ return x - y };
var operations = {
'+': plus, //-- This states that '+' contains the plus function.
'-': minus //-- This states that '-' contains the minus function.
};
var calculate = function(x, y, operation){ //-- operation makes it able to select a function from operations.
return operations[operation](x, y);
}
calculate(38, 4, '+'); //-- The '+' selects the plus function here.
calculate(47, 3, '-'); //-- The '-' selects the minus function here.
Executions will be something like this:
First argument is being passed as a key of the object and respective function is executed with arguments..
var calculate=function(x, y, operation)
{
//operations['+'](38, 4);
//operations['-'](47, 3);
return operations[operation](x, y);
};
Im just getting started on d3.js and was going through Nick's source code on github here and got stuck at the part where he is passing a function as data into d3.js.
The var x in the function assigned to next var gets incremented from 0 to the loop counter as i show in the jsbin link below. I cant quite wrap my head around how x gets incremented automatically and how does it know the loop counter that it needs to get incremented upto everytime.
the next variable is called from >> newdata from the >>render function ?
I just setup a jsbin here
This part:
.data(newData);
is simply going to call the newData function and bind the return to the selection.
So each call to render in the setInterval simply pushes the next function into his data array.
This part then:
selection.attr("class", "v-bar")
.style("height", function (d, i) {
return d(i) + "px"; // <- E
})
.select("span")
.text(function(d, i){
return d(i); // <- F
});
Calls d which is the next function for each element in the data array. It's passing the index position in the data array.
So the first render call is:
15 + 0 * 0;
Second is:
15 + 0 * 0;
15 + 1 * 1;
Third is:
15 + 0 * 0;
15 + 1 * 1;
15 + 2 * 2;
First, for simplification, this
var selection = d3.select("#container").selectAll("div")
.data(newData); // <- D
is just like writing
var arrayOfFunctions = newData();
var selection = d3.select("#container").selectAll("div")
.data(arrayOfFunctions); // <- D
So, for example, calling this code 3 times (via setInterval) builds up arrayOfFunctions like this:
arrayOfFunctions = [
function (x) { return 15 + x * x; },
function (x) { return 15 + x * x; },
function (x) { return 15 + x * x; }
]
(Note: it's not literally like that, because in actuality they're just pointers to the same function next)
So nothing about that increments x. But once it binds those functions to DOM elements (via data(arrayOfFunctions) and runs through this bit:
selection.attr("class", "v-bar")
.style("height", function (d, i) {
return d(i) + "px"; // <- E
})
d is function (x) { return 15 + x * x; } and i (which is 0, 1, or 2) is passed in as x to that function when it calls d(i).
And that's what essentially increments x.