I am trying to cache 'func.apply(this, func)' value so that it can be looked up later rather than running the function again. The problem is that I don't know how or what to use as the key.
Is there a way to assign an key of a function that can be looked up later?
Code example:
var m = function(func) {
var cached = {};
return function() {
var key = ''; // how do I get or create the key of func.apply(this, func)?
if (cached[key]) {
return cached[key];
}
cached[key] = func.apply(this, arguments);
return cached[key];
};
};
The m() function should return a function that, when called, will check if it has already computed the result for the given argument and return that value instead if possible.
What are you looking for is called Memoization
See: Implementing Memoization in JavaScript
Here are an example:
var myFunction = (function() {
'use strict';
var functionMemoized = function() {
// set the argumensts list as a json key
var cacheKey = JSON.stringify(Array.prototype.slice.call(arguments));
var result;
// checks whether the property was cached previously
// also: if (!(cacheKey in functionMemoized.cache))
if (!functionMemoized.cache.hasOwnProperty(cacheKey)) {
// your expensive computation goes here
// to reference the paramaters passed, use arguments[n]
// eg.: result = arguments[0] * arguments[1];
functionMemoized.cache[cacheKey] = result;
}
return functionMemoized.cache[cacheKey];
};
functionMemoized.cache = {};
return functionMemoized;
}());
Why do you need an object with an index. Just store the result/key.
var m = function(func) {
var result=null;
return function() {
if (result===null) {
result = func.apply(this, arguments);
}
return result;
}
};
But I am not sure that is what you want. If the function returns different values based on arguments, than you want to use a key based off the arguments.
var m = function(func) {
var results = {};
return function() {
var key = [].slice.call(arguments).join("-");
if (results[key]===undefined) {
results[key] = func.apply(this, arguments);
}
return results[key];
}
};
var multiply = function (a,b) {
return a * b;
}
var mult = m(multiply);
console.log(mult(2,5)); //runs calculation
console.log(mult(2,5)); //uses cache
If you send the value of the function as a string, you can use that as the index with one minor modification
var m = function(func, scope) {
return function() {
var cached = {};
var index = func; // how do I get or create the index of func.apply(this, func)?
scope = scope || this;
if (!cached[index]) {
func = scope[func]; //Get the reference to the function through the name
cached[index] = func.apply(this, func);
}
return cached[index];
};
};
This does depend on if the index exists in the this object reference. Otherwise you should use a different scope.
Related
var modularpattern = (function () {
var sum = 0;
return {
add: function () {
sum = sum + 1;
return sum;
},
}
} ());
var c = modularpattern;
c.add(); // 1
var d = modularpattern;
d.add(); // 2 but I want to be 1
console.log(modularpattern.add()); // alerts: 3
Is it possible to have more objects not only one? I want to have private fields but at the same time also having more that just one object?
Yes, that's easily possible by dropping the IIFE invocation to get a normal function instead. Only it's called factory pattern then, no longer module.
function factory() {
var sum = 0;
return {
add: function () {
sum = sum + 1;
return sum;
}
}
}
var c = factory();
c.add(); // 1
var d = factory();
d.add(); // 1
console.log(c.add()); // logs: 2
You can use the module pattern to create a factory which uses the module pattern to create more objects. Using your original example, it would look something like this:
var moduleFactory = (function() {
return {
create: function() {
return (function() {
var sum = 0;
return {
add: function() {
sum = sum + 1;
return sum;
}
}
})();
}
}
}
)();
var c = moduleFactory.create();
console.log(c.add()); //1
var d = moduleFactory.create();
console.log(d.add()); //1
I'm working on a tutorial that explains functional programming. He asked me to come with a solution and it worked, but his solution uses the .bind method of the function.
Is there a difference between our solutions other than the syntax?
function mapForEach(arr, fn) {
var newArr = [];
for(var i = 0; i < arr.length; i++){
newArr.push(fn(arr[i]));
}
return newArr;
}
var arr1 = [1,2,3,4,5];
var checkPassedLimitWithBind = function(limiter){
return function (limiter, item) {
return item >= limiter;
}.bind(this, limiter);
};
var checkPassedLimitWithClosure = function(limiter){
return function (item) {
return item >= limiter;
};
};
var notPassed3 = mapForEach(arr1, checkPassedLimitWithBind(3));
var doesNotPass3 = mapForEach(arr1, checkPassedLimitWithClosure(3));
alert(notPassed3);
alert(doesNotPass3);
The examples can be found here as well:
https://jsfiddle.net/podbarron/73m86cj3/
There is absolutely no behavior difference because that function does not use this.
Otherwise it would be different, yes:
var checkPassedLimitWithBind = function(limiter) {
return function (limiter, item) {
return this == item;
}.bind(this, limiter);
};
var checkPassedLimitWithClosure = function(limiter) {
return function (item) {
return this == item;
};
};
console.log( checkPassedLimitWithBind.call(123)(123) ); // true
console.log( checkPassedLimitWithClosure.call(123)(123) ); // false
The bind solution is unnecessarily complicated. There's no need to partially apply the limiter value there since the function can pretty much access it directly.
Both will end up working the same way. However, it can be different if the variable ever gets reassigned (you'd never want to do it with function arguments).
var checkPassedLimitWithBind = function(limiter){
var fn = function (limiter, item) {
return item >= limiter;
//limiter === argument value for limiter parameter
}.bind(this, limiter);
limiter = 5;
return fn;
};
var checkPassedLimitWithClosure = function(limiter){
var fn = function (item) {
return item >= limiter;
//limiter === 5 all the time
};
limiter = 5;
return fn;
};
Answering the post title: Basically, the closure will have access to whatever value that reference is holding. When you bind the function you'll get that specific value passed down.
I am using this code -
var gArray = (function (value) {
var array = [];
return function () {
array.push(value);
return array;
}
}());
gArray(1);
gArray(2);
gArray(3);
I am expecting to this code snippet [1, 2, 3]
but i am getting [undefined, undefined, undefined]
The gArray function doesn't have an argument, the immediately invoked function does, but you pass nothing when you call it:
var gArray = (function (value) { //<- Argument of IIFE
var array = [];
return function () { //<- No arguments for gArray
array.push(value);
return array;
}
}()); //<- No arguments passed to IIFE
What you need is to define an argument for the returned function, which is gArray:
var gArray = (function () {
var array = [];
return function (value) {
array.push(value);
return array;
}
}());
Your outer function is a self-invoked function. That means that it will be executed as soon as () is reached. In this particular case, it's returning:
function () {
array.push(value);
return array;
}
which is taking value as undefined. To solve this issue, you can rewrite your code as follows:
var gArray = (function () {
var array = [];
return function (value) {
array.push(value);
return array;
}
}());
Change var array = []; to this.array = [];.
It needs to have the right scope.
var myArray = [];
function addToArray(value){
myArray.push(value);
console.log(value + " was added to " + myArray);
}
addToArray(1);
addToArray(2);
addToArray(3);
If you give back myArray console will say [1, 2, 3]
This is the best way to do it:
const array = [];
const pushArray = function(value, array) {
array.push(value);
return array;
};
pushArray(1, array);
pushArray(2, array);
pushArray(3, array);
So I'm using $.extend to combine multiple components (objects). Some of these components have a function with the same key. I want the final extended object to have that same key, but have it point to a function which calls all of the merged components' versions of the functions one after the other.
So it'd look something like this:
var a = { foo: function() { console.log("a"); } };
var b = { foo: function() { console.log("b"); } };
var c = {}; // Doesn't have foo
var d = $.extend({}, a, b, c);
var e = $.extend({}, a, c);
var f = $.extend({}, c);
d.foo(); // Should call function() { console.log("a"); console.log("b"); }
e.foo(); // Should call function() { console.log("a"); }
f.foo(); // Should call function() {}
Is there a pragmatic way of doing this? I only want to do this for a specific set of keys, so I would only want to merge those specific keys' functions together and let the ordering in extend overwrite anything else.
Hopefully that makes sense :S
Note
f.foo(); // Should call function() {}
object c does not appear to have property foo . callling f.foo() returns TypeError: undefined is not a function . Not certain if requirement to add foo function to extended f object , or return object c (empty object) from anonymous function ? At piece below , foo function not added to extended f object.
jquery $.Callbacks() utilized to add functions having foo property at $.each()
Try
var a = { foo: function() { console.log("a"); } };
var b = { foo: function() { console.log("b"); } };
var c = {}; // Doesn't have foo
//d.foo();
// Should call function() { console.log("a"); console.log("b"); }
//e.foo();
// Should call function() { console.log("a"); }
//f.foo();
// Should call function() {}
var callbacks = $.Callbacks();
var arr = [], d, e, f;
$.each([a,b,c], function(k, v, j) {
var j = [a,b,c];
// filter objects having `foo` property
if (v.hasOwnProperty("foo")) {
arr.push([v, v.foo]);
if (arr.length > 1) {
callbacks.add(arr[0][1], arr[1][1]);
// `add` `foo` properties to `callbacks`
// `fire` both `callbacks` when `object.foo` called
j[k -1].foo = callbacks.fire;
d = $.extend({}, j[k - 1])
} else {
// `else` extend original data (`fn`, `object`)
// contained within object
e = $.extend({}, j[k + 1]);
f = $.extend({}, j[++k + 1]);
}
}
});
d.foo(); // `a` , `b`
e.foo(); // `b`
console.log(f); // `Object {}`
f.foo() // `TypeError: undefined is not a function`
jsfiddle http://jsfiddle.net/guest271314/3k35buc1/
See jQuery.Callbacks()
Here's what I ended up with based off of guest271314's answer. toMix is the array of components to be mixed into the object. I actually didn't need the dummy functions I thought I might, and I ended up using an array of functions instead of the $.Callbacks() so that I could control the order in which the functions are called. I also needed to use the call() function so that I could call the functions from the correct this object.
this.functionMerge = function(toMix) {
var callbacks = {};
var functions = {};
var obj = {};
var keys = [
'componentWillMount',
'componentDidMount',
'componentWillUpdate',
'componentDidUpdate',
'componentWillUnmount'
]
$.each(keys, function(key, value) {
callbacks[value] = [];
});
for (i = 0; i < toMix.length; ++i) {
$.each(keys, function(key, value) {
if (toMix[i].hasOwnProperty(value) && typeof toMix[i][value] == 'function') {
callbacks[value].push(toMix[i][value]);
}
});
$.extend(true, obj, toMix[i]);
}
$.each(keys, function(key, value) {
functions[value] = function() {
var that = this;
$.each(callbacks[value], function(key, value) {
value.call(that);
});
};
});
return $.extend(true, obj, functions);
}
Let's say I have a JavaScript object:
function a(){
var A = [];
this.length = function(){
return A.length;
};
this.add = function(x){
A.push(x);
};
this.remove = function(){
return A.pop();
};
};
I can use it like so:
var x = new a();
x.add(3);
x.add(4);
alert(x.length()); // 2
alert(x.remove()); // 4
alert(x.length()); // 1
I was trying to make .length not a function, so I could access it like this: x.length, but I've had no luck in getting this to work.
I tried this, but it outputs 0, because that's the length of A at the time:
function a(){
var A = [];
this.length = A.length;
//rest of the function...
};
I also tried this, and it also outputs 0:
function a(){
var A = [];
this.length = function(){
return A.length;
}();
//rest of the function...
};
How do I get x.length to output the correct length of the array inside in the object?
You could use the valueOf hack:
this.length = {
'valueOf': function (){
return A.length;
},
'toString': function (){
return A.length;
}
};
Now you can access the length as x.length. (Although, maybe it's just me, but to me, something about this method feels very roundabout, and it's easy enough to go with a sturdier solution and, for example, update the length property after every modification.)
If you want A to stay 'private', you need to update the public length property on every operation which modifies A's length so that you don't need a method which checks when asked. I would do so via 'private' method.
Code:
var a = function(){
var instance, A, updateLength;
instance = this;
A = [];
this.length = 0;
updateLength = function()
{
instance.length = A.length;
}
this.add = function(x){
A.push(x);
updateLength();
};
this.remove = function(){
var popped = A.pop();
updateLength();
return popped;
};
};
Demo:
http://jsfiddle.net/JAAulde/VT4bb/
Because when you call a.length, you're returning a function. In order to return the output you have to actually invoke the function, i.e.: a.length().
As an aside, if you don't want to have the length property be a function but the actual value, you will need to modify your object to return the property.
function a() {
var A = [];
this.length = 0;
this.add = function(x) {
A.push(x);
this.length = A.length;
};
this.remove = function() {
var removed = A.pop();
this.length = A.length;
return removed;
};
};
While what everyone has said is true about ES3, that length must be a function (otherwise it's value will remain static, unless you hack it to be otherwise), you can have what you want in ES5 (try this in chrome for example):
function a(){
var A = [],
newA = {
get length(){ return A.length;}
};
newA.add = function(x){
A.push(x);
};
newA.remove = function(){
return A.pop();
};
return newA;
}
var x = a();
x.add(3);
x.add(4);
alert(x.length); // 2
alert(x.remove()); // 4
alert(x.length); // 1
You should probably use Object.create instead of the function a, although I've left it as a function to look like your original.
I don't think you can access it as a variable as a variable to my knoledge cannot return the value of a method, unless you will hijack the array object and start hacking in an update of your variable when the push/pop methods are called (ugly!). In order to make your method version work I think you should do the following:
function a(){
this.A = [];
this.length = function(){
return this.A.length;
};
this.add = function(x){
this.A.push(x);
};
this.remove = function(){
return this.A.pop();
};
};
These days you can use defineProperty:
let x = {}
Object.defineProperty(x, 'length', {
get() {
return Object.keys(this).length
},
})
x.length // 0
x.foo = 'bar'
x.length // 1
Or in your specific case:
Object.defineProperty(x, 'length', {
get() {
return A.length
}
})
function a(){
this.A = [];
this.length = function(){
return this.A.length;
};
this.add = function(x){
this.A.push(x);
};
this.remove = function(){
return this.A.pop();
};
};