Jump to content

Javascript How can I use a function in a function?

G1K777

Hi,

I want to use a custom function inside a function.

Not something like this.
 

function myFunction(){
   function secondFunction(x){
    console.log(x)
   }
}

I want to pass a custom function into another function.

Array.prototype.loop = function(f){
    for(i = 0; i < this.length; i++){
        return this[i];
    }
}

function test(x){
  // this is just a example.
    console.log(x);
}
arr.loop(test());

Should work similar to "forEach" where you pass a function inside.

myArray.forEach(function(x) {
  console.log(x);
});

 

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

21 minutes ago, duncannah said:

Like this?


function test(func) {
    if (typeof func === "function")
        func();
}

Not like this. There are exmaples above what I'm looking for.

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

Like this?

function test(func)
{
    if (typeof func !== "function")
    {
        return;
    }
    for (let i = 0; i < 10; i++)
    {
        func(i);
    }
}

test(function(x) {
   console.log(x);
});

It is really just what duncannah said, but with a small expansion. If this is not what you are looking for you should describe your problem more clearly. And also why you want to use it in this specific way.

Link to comment
Share on other sites

Link to post
Share on other sites

Okay got it, thanks guys :D

 

Array.prototype.loop = function(func)
{
    let l = this.length;
    for( let i = 0; i < l; i++ ){
        func(this);
    }
}

arr.loop(function(x) {
   console.log(x);
});

 

(( Can't post it as code for some reason ))

I wonder why it's so slow.

http://jsben.ch/3H35T

 

// EDIT

 

Tested it in Firefox Nightly and the results are different.

The "for of" loop needs ~3ms to loop about 6.7k values.

My prototype function needs about 0.11ms.

That's what my browser says. Did 6 tests and it's always the same.

test.js

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

Your test on that test site is flawed, you should have declared the array.prototype function in the setup.  Right now its doing it ever test which will slow it down alot. And pre declaring the function and not as an argument can speed things up a bit aswell.

http://jsben.ch/3H35T


 

(function() {
    // Generate the test array with random strings
    let arr = [];
    for (let i = 0; i < 100000; i++) {
        arr[i] = Math.random().toString(36).substring(2, 3 + Math.floor(Math.random() * 9));
    }

    Array.prototype.loop = function(func) {
        let l = this.length;
        for (let i = 0; i < l; i++) {
            func(this[i]);
        }
    }
    const add = (x)=>o += x;

    let o = '';
    var loop;

    console.time(loop = 'Loop - for -')
    for (let i of arr) {
        add(i);
    }
    console.timeEnd(loop);

    o = '';
    console.time(loop = 'Loop - prototype -')
    arr.loop(add);
    console.timeEnd(loop);

    // console.log(o)
    console.log('Array length', arr.length);

}
)();

One browser is faster at one and the other the other...hehe, this is the point where people tell you that micro benchimarking is a fools game and most of the time its just best to write code thats easiest to read, debug, test, blah, blah.  And most of the time they're right.

Link to comment
Share on other sites

Link to post
Share on other sites

But how? When I use the forEach loop and look at the time in the consoles performance tab (Firefox). It says 1ms vs my prototypes 1.4ms.
But in your example it looks like my code is faster.. O.o

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

I improved the code a bit and now it's always faster than the for loop by 2x-3x.

Loop - prototype -: 5ms script.js:30:1
Loop - for -: 12ms script.js:45:1
Array length 100000
 
minimalizing it with a compressor reduces the avg time by 1ms. So it's 4ms for the prototype and 1-2ms less for the for in loop.
(function() {
    // Set variables
    const add = (x)=>o+=x;
    let arr = [],
        o = '',
        loop;

    // Generate the test array with random strings
    for (let i = 0; i < 100000; i++) {
        arr[i] = Math.random().toString(36).substring(2, 3 + Math.floor(Math.random() * 9));
    }

    Array.prototype.loop = function(func) {
        let l = this.length,
            i = 0;
        for (; i < l;) {
            func(this[i]);
            i++;
        }
    }


    // Prototype
    o = '';
    console.time(loop = 'Loop - prototype -')
    arr.loop(add);
    o = '';
    arr.loop(add);
    o = '';
    arr.loop(add);
    console.timeEnd(loop);

    // for loop
    console.time(loop = 'Loop - for -')
    for (let i of arr) {
        add(i);
    }
    o = '';
    for (let i of arr) {
        add(i);
    }
    o = '';
    for (let i of arr) {
        add(i);
    }
    console.timeEnd(loop);

    // console.log(o)
    console.log('Array length', arr.length);

}
)();

deleting the anon si function at the beginning, improves the for in loop a bit, makes it more constant. So it doesn'g go:

Loop - prototype -: 5ms script.js:30:1
Loop - for -: 37ms script.js:45:1
Array length 100000

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

Sorry for "spamming" but I can't add code when editing posts.
Here is also another test. It loops out every value into a div. Not everything at once, but each single value from the array at time.

Loop - prototype -: 54ms script.js:33:1
Loop - for -: 84ms script.js:50:1
Array length 1000
 
Why this test? Imagine looping a huge table with "Game Items" "Articles" etc.
 
The other thing is also that the for of loop has error checking, my loop is just = speed.
 
// Set variables
const demo = document.getElementById('demo'),
       add = (x)=>demo.innerHTML+=x;
let arr = [],
    o = '',
    loop;

// Generate the test array with random strings
for (let i = 0; i < 1000; i++) {
    arr[i] = Math.random().toString(36).substring(2, 3 + Math.floor(Math.random() * 9));
}

Array.prototype.loop = function(func) {
    let l = this.length,
        i = 0;
    for (; i < l;) {
        func(this[i]);
        i++;
    }
}


// Prototype
o = '';
console.time(loop = 'Loop - prototype -')
arr.loop(add);
demo.innerHTML = '';
o = '';
arr.loop(add);
demo.innerHTML = '';
o = '';
arr.loop(add);
console.timeEnd(loop);

// for loop
console.time(loop = 'Loop - for -')
for (let i of arr) {
    add(i);
}
demo.innerHTML = '';
o = '';
for (let i of arr) {
    add(i);
}
demo.innerHTML = '';
o = '';
for (let i of arr) {
    add(i);
}
console.timeEnd(loop);

// console.log(o)
console.log('Array length', arr.length);

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

7 hours ago, G1K777 said:

Sorry for "spamming" but I can't add code when editing posts.

You can just type [ code ] [/ code ] without the spaces to add code.

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×