Calling a returned function - javascript

So I am trying to write a general memoizing function in Javascript, using this as my reference material. I've implemented it as instructed:
function memoize(func) {
var memo = {};
var slice = Array.prototype.slice;
return function() {
var args = slice.call(arguments);
if (args in memo)
return memo[args]
else
return (memo[args] = func.apply(this, args));
}
}
function fibonacci(n) {
if (n === 0 || n === 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
function memoFib = memoize(fibonacci);
console.log("Fibonacci of 6 is " + memoFib(6));
but for the life of me I cannot remember the proper syntax to calling the memoized function. How do I do this? How do I generalize this so that it's the memoized fibonacci function which is always called instead of the original function fibonacci?

You're almost there; you just need to fix your syntax when creating the memoized function. Instead of function memoFib =, do var memoFib = (or if ES2015 is an option, const would be better than var). And presumably you'll want to have the recursion calling into the memoized version as well, so i updated those as well. In the following code it may look weird that i'm referencing memoFib on a line that comes earlier than the line with var memoFib but javascript allows that due to hoisting.
function memoize(func) {
var memo = {};
var slice = Array.prototype.slice;
return function() {
var args = slice.call(arguments);
if (args in memo)
return memo[args]
else
return (memo[args] = func.apply(this, args));
}
}
function fibonacci(n) {
if (n === 0 || n === 1)
return n;
else
return memoFib(n - 1) + memoFib(n - 2);
}
var memoFib = memoize(fibonacci);
console.log("Fibonacci of 6 is " + memoFib(6));
And if you want to make absolutely sure no one can ever invoke the nonmemoized version, then you can hide it inside of an IIFE:
const fibonacci = (function () {
function unmemoizedVersion(n) {
if (n === 0 || n === 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
return memoize(unmemoizedVersion);
})();

Related

How can i reduce the time of execution of this code

var yourself = {
fibonacci : function(n) {
return n === 0 ? 0 : n === 1 ? 1 :
this.fibonacci(n -1) + this.fibonacci (n-2)
}
};
This function is constantly setting the value of its 'fibonacci' property based on the
arguement supplied for 'n' parameter of the function.
I would like to refactor the function to reduce execution time
Using dynamic programming, Memoization that cache the already calculated result
read more about memoization here
const memoFib = function () {
let memo = {}
return function fib(n) {
if (n in memo) { return memo[n] }
else {
if (n <= 1) { memo[n] = n }
else { memo[n] = fib(n - 1) + fib(n - 2) }
return memo[n]
}
}
}
const fib = memoFib()
console.log(fib(50));
You could implement some kind of caching. This way you don't need to recalculate the same result multiple times.
var yourself = {
fibonacci : function(n, cache = new Map()) {
if(cache.has(n)) return cache.get(n);
if(n === 0) return 0;
if(n === 1) return 1;
const start = this.fibonacci(n-1, cache);
const end = this.fibonacci(n-2, cache);
cache.set(n-1, start);
cache.set(n-2, end);
return start + end;
}
};
console.log(yourself.fibonacci(40));

Trying to make a repeater function using only higher order functions?

I'm trying to make a function that accepts another function and outputs that function repeatedly by only using function expressions/applications.
So far I have a function twice which accepts another function as an argument and returns func(func(x)):
function twice(func) {
function x(x) {
return func(func(x));
}
return x;
}
I'm trying to make a repeater function such that const thrice = repeater(twice) returns func(func(func(x))), and const fourtimes = repeater(thrice) etc. but i'm confused as to how to do this. Any help would be appreciated greatly. Thank you
Using your current structure thats impossible as twice does not expose a reference to func, thus repeater cannot call it.
The only solution I could think of would be to leak func from the inside through a (hidden) property:
const r = Symbol();
const repeater = f => Object.assign(
v => f[r] ? f(f[r](v)): f(v),
{ [r]: f[r] || f }
);
const addThree = repeater(repeater(repeater(n => n + 1)));
console.log(addThree(10));
You should two base cases (if n == 0 => exit, if n == 1 => return f(x)), where n is an additional parameter that specifies how many times the function should repeat with the arguments args:
function repeater(func, x, n) {
if (n == 0) return;
if (n == 1) return func(x);
else {
return func(repeater(func, x, --n));
}
}
let sqr = n => n * n;
console.log(repeater(sqr, 2, 3));
Do you look for something like this?
function chain(f, g) {
return function (x) {
return f(g(x));
}
}
function ntimes(f, n) {
if (n == 0) {
return function (x) { return x }
} else {
return chain(f, ntimes(f, n-1));
}
}
This will make a new function which repeats the original function f n times.

Calculations from array values and operators

I'm learning JavaScript and one of my challenges is to make a calculator without using eval() function.. So far I made inputs, input checking, etc. and I get an array that looks somewhat like this numbers = ['-','1','+','2','*','3','+','(','5','/','2'comma','5',')','+','6']; And since I'm still learning, I have no idea where to go from this.. How do i do the math on this string? How do i prioritize the calculations in ( ), *, / ? What technique should i use to solve this problem? I'm not looking for a ready to go answer, I want to write it myself, I need guidance on how to do this :)
Link to my current code in JSFiddle. so far I'm using the string to display the keys pressed.
var rezult = "0";
var numberJoin = [];
function skaicius(symbol) {
numberJoin.push(symbol);
secondTolast = numberJoin[numberJoin.length - 2];
lastNumber = numberJoin[numberJoin.length - 1];
symbolswithoutComma = numberJoin.toString();
atsakymas = symbolswithoutComma.replace(/,/g, "");
atsakymas = atsakymas.replace(/comma/g, ",");
if (numberJoin[0] === "x" || numberJoin[0] === "+") {
numberJoin = [];
} else if ((symbol === "x" || symbol === "+" || symbol === "-") && (secondTolast === "x" || secondTolast === "+" || secondTolast === "-")) {
numberJoin.splice(numberJoin.length - 2, numberJoin.length - 1);
numberJoin.push(symbol);
} else if (symbol === "delete") {
numberJoin = [];
rezult = "0";
document.getElementById("rezult").innerHTML = rezult;
} else if (symbol === "=") {
} else {
document.getElementById("rezult").innerHTML = atsakymas;
}
}
EDIT: eval() and things like new function('return -1+2*3+(5/2,5)+6')() are a bit of cheats and since I'm learning, I'd like to try solving this problem without cheating :)
There are so many well known algorithms which help in evaluating the expression.
using stack data structure you can push operators and operands in to array.
pop them in order form array to produce value for the given expression.
get some idea on infix,prefix and postfix notation of expression.
start with binary operations +,-,%,* and then enhance to incorporate parenthesis ()
Maybe you are looking for this, a collection of functions and a stack based iteration over the commands in a RPN style.
In the output you see the actual command and stack.
var $ = {
'===': function (b) { return function (a) { return a === b; }; },
'+': function (b) { return function (a) { return a + b; }; },
'-': function (b) { return function (a) { return a - b; }; },
'1/x': function (a) { return 1 / a; },
},
commands = [3, 2, '+', 9, 4, '-', '==='],
result = commands.reduce(function (stack, command) {
var temp;
if ($[command]) {
temp = $[command];
while (typeof temp === 'function') {
temp = temp(stack.pop());
}
stack.push(temp);
} else {
stack.push(command);
}
document.write('<pre>' + command + ': ' + JSON.stringify(stack, 0, 4) + '</pre>');
return stack;
}, [])[0];
document.write(result);

How do you curry any javascript function of arbitrary arity?

Let's say I have some function:
function g(a,b,c){ return a + b + c }
And I'd like to turn it into its "curried" form (in quotations since it's not exactly curried per se):
function h(a,b,c){
switch(true){
case (a !== undefined && b !== undefined && c !== undefined):
return a + b + c
case (a !== undefined && b !== undefined && c === undefined):
return function(c){ return a + b + c }
case (a !== undefined && b == undefined && c === undefined ):
return function(b,c){
return (c === undefined) ? function(c){ return a + b + c } : a + b + c
}
default:
return h
}
}
The above form has the partial binding behavior I want:
h(1) -> h(b,c)
h(1,2) -> h(c)
h(1,2,3) -> 6
h() -> h(a,b,c)
Now I'd like to automate this process into some generic function curry such that given any un-curried function (and maybe its number of parameters), the above function is generated. But I'm not quite sure how to implement it.
Alternatively, if the following form could be automatically created, it'd be also interesting:
function f(a,b,c){
return function(a){ return function(b){ return function(c){ return a + b + c }}}
}
Though binding f looks like this:
f(1)(2)(3) = 6
so it is very unwieldily and non-idiomatic, but creating the above form seem more feasible to me.
Now is could any of the above form be generated by some function, if so, how?
I believe that you could simply use Function.prototype.bind. That gives you all the flexibility you need, wheter you want the result of the function right away or simply push another value into the arguments until you decide to execute.
function sum() {
return [].reduce.call(arguments, function (c, n) {
return c + n;
});
}
sum(1, 2); //3
var sum2 = sum.bind(null, 1, 2);
sum2(); //3
var sum3 = sum2.bind(null, 3);
sum3(); //6
You could also use a helper function like:
function curry(fn) {
var c = curry.bind(this, fn = fn.bind.apply(fn, [this].concat([].slice.call(arguments, 1))));
c.exec = fn;
return c;
}
curry(sum, 1, 2)(3)(4, 5)(6, 7, 8).exec(); //36
Also this is very flexible as you do not have to chain, you can re-use the same curried function.
var sumOnePlus = curry(sum, 1);
sumOnePlus.exec(2); //3;
sumOnePlus.exec(3); //4;
Here's my attempt:
function curry(fn, len) {
if (typeof len != "number")
len = fn.length; // getting arity from function
return function curried() {
var rlen = len - arguments.length;
if (rlen <= 0) // then execute now
return fn.apply(this, arguments);
// else create curried, partially bound function:
var bargs = [this]; // arguments for `bind`
bargs.push.apply(bargs, arguments);
return curry(fn.bind.apply(fn, bargs), rlen);
};
}
This does not partial application (which is easy in JS with the bind method), but true functional currying. It works with any functions of arbitrary, but fixed arity. For variadic functions you would need a different execution trigger, maybe when no arguments are passed any more or an exec method like in #plalx' answer.
How about something like this:
function makeLazy(fn) {
var len = fn.length;
var args = [];
return function lazy() {
args.push.apply(args, arguments);
if (args.length < len) {
return lazy;
} else {
return fn.apply(this, args);
}
}
}
function f(a,b,c) { return a + b + c; }
var lazyF = makeLazy(f);
lazyF(1)(2)(3); // 6
var lazyF = makeLazy(f);
lazyF(1,2)(3); // 6
If you wanted a reusable function (I guess I can't tell exactly what you want), then this would work:
function makeCurry(fn) {
return function curry() {
var args = [].slice.call(arguments);
return function() {
return fn.apply(this, args.concat.apply(args, arguments));
};
}
}
function f(a,b,c) { return a + b + c; }
var curryF = makeCurry(f);
var addOneTwoAnd = curryF(1,2);
addOneTwoAnd(3); // 6
addOneTwoAnd(6); // 9
Please check the curry library.
It can turn any function into curry no matter how many arguments are there.
Example:
> var curry = require('curry');
undefined
> var add = curry(function(a, b, c, d, e) { return a + b + c + d + e; });
undefined
> add(1)
[Function]
> add(1,2,3,4,5)
15
> add(1,2)(3,4)(5)
15
>
The bind() method on function lets you bind the this inside the function as well as bind extra parameters. So, if you pass null for the this parameter, you can use bind() to curry the parameters into the function.
function g(a,b,c){ return a + b + c }
var g_1 = g.bind(null, 1);
console.log(g_1(2, 3)); // Prints 6
var g_1_2 = g.bind(null, 1, 2);
console.log(g_1_2(3)); // Prints 6
Check Javascript Function bind() for details and interactive examples of using bind() to bind parameters.

Undefined in associative array lookup

var candidates = {
"1":"Barack Obama",
"2":"Mitt Romney",
"3":"Dennis Kucinich",
"4":"Quentin Tarantino",
"5":"Count Dracula"
};
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
function getRandomPresident(){
var num = getRandomInt(1, Object.size(candidates));
if (num!=5){
alert(num);
var key = num.toString();
var res = candidates[key];
return res;
} else {
getRandomPresident();
}
}
alert(getRandomPresident());
This code works, but sometimes after generating random value it outputs "undefined" instead of the name - http://jsbin.com/uriwal/edit#source Why?
When trying again (the else block), you don't return the new value. You should pass the return value through:
return getRandomPresident();
Currently, you're picking a new item, but as the function doesn't return it, the return value is undefined.
I'm guessing the getRandomInt() function can return 0, which your associative array does not have. Just create a tighter check in the if clause:
if (num >= 1 && num <= 5) {
// do stuff
}
EDIT:
Scratch that, you have getRandomInt(1, max). In any case, why even have a recursive function? Just do this:
var num = 0;
while ((num = getRandomInt(1, ...)) > 5) {
num = getRandomInt(1, ...);
}
// return the resource
Hope this helps
Change function to this:
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min)) + min;
}

Categories