Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,332 members, 7,808,148 topics. Date: Thursday, 25 April 2024 at 07:48 AM

Brain Teaser: Recursive Anonymous Function Expression Analysis - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Brain Teaser: Recursive Anonymous Function Expression Analysis (1324 Views)

Php Function To Generate A Random Expression / User Defined Function To Validate Regular Expression In Javascript / Regular Expression Validation In Javascript (2) (3) (4)

(1) (Reply) (Go Down)

Brain Teaser: Recursive Anonymous Function Expression Analysis by romme2u: 1:51am On Oct 20, 2018
I have over-studied in recent weeks as I’ve read more than I write (code) grin grin

There is a technique that has been flying over my head for over a year (probably because I didn’t take it serious at first). I came across it in Douglas Crockford’s “JavaScript the Good Parts” while studying advanced function techniques late last year. Here is a sample:


//JS Memoization
//memo is a one dimensional array for storing pre-defined numbers.......
//the function returns a value if it already exists in the array.......
//.......else generate and store a value for future use, then return the generated value
var memoizer = function (memo, fundamental) {
var shell = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fundamental(shell, n);
memo[n] = result;
}
return result;
};
return shell;
};
//fundamental function can be a Factorial, Fibonacci series generator, fetching data over a network or any processor intensive task



Here is it counterpart in PHP (Source – User Comment on PHP online manual):


//PHP Multi-Dimension Array Restructuring --- handles 2D to nD arrays as memory permits
//Designed to rearrange $_FILES superglobal from associative to numeric array when multiple files are uploaded at once
function get_fixed_files() {
$function = function($files, $fixed_files = [], $path = []) use (&$function) {
foreach ($files as $key => $value) {
$temp = $path;
$temp[] = $key;

if (is_array($value)) {
$fixed_files = $function($value, $fixed_files, $temp);
} else {
$next = array_splice($temp, 1, 1);
$temp = array_merge($temp, $next);

$new = &$fixed_files;

foreach ($temp as $key) {
$new = &$new[$key];
}

$new = $value;
}
}

return $fixed_files;
};

return $function($_FILES);
}


Both piece of code uses same technique (Recursive Anonymous Function Expression) to solve two different problems. My issue is not recursive functions as I understand the concept. But since recursive function usually suffers from memory constraint and can most time be rewritten as iterative, I have never used it as iteration presents a more readable code to me.

It seems the PHP code uses the Tower of Hanoi concept to rearrange the data structure. It is just a guess, I’m not really sure.

Modified

Thanks Nmeri17, the question didn't fit the Q&A format required by stack overflow.........I just needed to reword the question, sorry for the oversight.

I have also provided context and expected data structure

The correct question should be Convert these Recursive functions to Iterative functions (rewrite as)

I understand that some problems suit recursive technique more than iterative but i just need an insight
Re: Brain Teaser: Recursive Anonymous Function Expression Analysis by romme2u: 1:56am On Oct 20, 2018
embarassed
Re: Brain Teaser: Recursive Anonymous Function Expression Analysis by Nmeri17: 8:51am On Oct 22, 2018
If you posted this on stack overflow, they're going to maim you with downvotes. You're seeking for help on an algorithm; didn't post your efforts on it so far, didn't mention the use case, didn't even as much as supply the arguments for your convoluted functions. Idk why I spent the last few hours on it. I literally reverse engineered the puzzle to come up with its arguments. Solving it was easier. I've added a couple comments so you can see what I'm doing


var arr = [

{charLen:['boobs','of', 'viv..'],randObj: ['push', 'your', 'limit'], views: 5},

{charLen: ['nmeri', 'chukwu', 'legend of all tym'], randObj: ['op is a fat donke'], longer: ['shell dynamism', 'thiswontbeomitted', {amy:'deep search will not respond'}], views:17}

],

newData = path = [];

for(var a = 0; a <arr.length;a++) {

var init = memoizer(arr[a], (mental,index) => {

var ctxView = mental('views'),

myShell =arr;

for (var d =0;d <path.length;d++) myShell = myShell[path[d]];

// your fundamental can do anything. here, I'm returning the element whose length matches the shell's view
return myShell.filter(c => c.length == ctxView)[0]; // need access to contextual views
}),

keys = Object.keys(arr[a]);


for(var b = 0; b < keys.length;b++) {


path = [a, keys[b]]; // populate this as as required. i imagine the data set will have random dimensions in each node but this is enough algorithming for one day. hint: you'll need another recursive function to grab all nested structures

newData.push(init(keys[b]));

}
}

console.log(newData)


I'm afraid, the PHP solution will have to come some other time. I never reach to debug PHP code with phone sad

BTW this is not a true anonymous function. It's recursing closures with higher order functions. If I show you a proper recursive anonymous function, you won't even be given variables like shell. The only thing you'll see is one entry point. How do you invoke a function tied to "nothing"? wink

1 Like

Re: Brain Teaser: Recursive Anonymous Function Expression Analysis by talk2hb1(m): 9:33pm On Oct 22, 2018
romme2u:
I have over-studied in recent weeks as I’ve read more than I write (code); mostly package management and version control tools as I prepare for large-scale code collaboration and deployment of complex projects (actually I am preparing to port a Drupal 7 module to Drupal 8 for a start).

There is a technique that has been flying over my head for over a year (probably because I didn’t take it serious at first). I came across it in Douglas Crockford’s “JavaScript the Good Parts” while studying advanced function technique late last year. Here is a sample:

//JS Memoization
var memoizer = function (memo, fundamental) {
var shell = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fundamental(shell, n);
memo[n] = result;
}
return result;
};
return shell;
};


Here is it counterpart in PHP (Source – User Comment on PHP online manual):

//PHP Multi-Dimension Array Restructuring
function get_fixed_files() {
$function = function($files, $fixed_files = [], $path = []) use (&$function) {
foreach ($files as $key => $value) {
$temp = $path;
$temp[] = $key;

if (is_array($value)) {
$fixed_files = $function($value, $fixed_files, $temp);
} else {
$next = array_splice($temp, 1, 1);
$temp = array_merge($temp, $next);

$new = &$fixed_files;

foreach ($temp as $key) {
$new = &$new[$key];
}

$new = $value;
}
}

return $fixed_files;
};

return $function($_FILES);
}

Both piece of code uses same technique (Recursive Anonymous Function Expression) to solve two different problems. My issue is not recursive functions as I understand the concept perfectly. But since recursive function usually suffers from stack overflow (in some languages) and can be rewritten as iterative, I have never used it as iteration presents a more readable code.

It seems the PHP code uses the Tower of Hanoi concept to rearrange the data structure. It is just a guess, I’m not really sure.

Can anyone help me breakdown the code as the thing nearly crash my head.

seun, kodewrita, codehouse, kobojunkie talk2hb1
??
Re: Brain Teaser: Recursive Anonymous Function Expression Analysis by CodeHouse: 11:06pm On Oct 26, 2018
romme2u:
I have over-studied in recent weeks as I’ve read more than I write (code); mostly package management and version control tools as I prepare for large-scale code collaboration and deployment of complex projects (actually I am preparing to port a Drupal 7 module to Drupal 8 for a start).

There is a technique that has been flying over my head for over a year (probably because I didn’t take it serious at first). I came across it in Douglas Crockford’s “JavaScript the Good Parts” while studying advanced function technique late last year. Here is a sample:

//JS Memoization
var memoizer = function (memo, fundamental) {
var shell = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fundamental(shell, n);
memo[n] = result;
}
return result;
};
return shell;
};


Here is it counterpart in PHP (Source – User Comment on PHP online manual):

//PHP Multi-Dimension Array Restructuring
function get_fixed_files() {
$function = function($files, $fixed_files = [], $path = []) use (&$function) {
foreach ($files as $key => $value) {
$temp = $path;
$temp[] = $key;

if (is_array($value)) {
$fixed_files = $function($value, $fixed_files, $temp);
} else {
$next = array_splice($temp, 1, 1);
$temp = array_merge($temp, $next);

$new = &$fixed_files;

foreach ($temp as $key) {
$new = &$new[$key];
}

$new = $value;
}
}

return $fixed_files;
};

return $function($_FILES);
}

Both piece of code uses same technique (Recursive Anonymous Function Expression) to solve two different problems. My issue is not recursive functions as I understand the concept perfectly. But since recursive function usually suffers from stack overflow (in some languages) and can be rewritten as iterative, I have never used it as iteration presents a more readable code.

It seems the PHP code uses the Tower of Hanoi concept to rearrange the data structure. It is just a guess, I’m not really sure.

Can anyone help me breakdown the code as the thing nearly crash my head.

seun, kodewrita, codehouse, kobojunkie talk2hb1

Firstly, don't over study again and don't crash your head.

Secondly, bring your question to Nairaland, not that we don't have great minds here but codes are better interpreted with no smileys
Re: Brain Teaser: Recursive Anonymous Function Expression Analysis by Luminee(f): 11:20pm On Oct 26, 2018
CodeHouse:


Firstly, don't over study again and don't crash your head.

Secondly, bring your question to Afri coders, not that we don't have great minds here but codes are better interpreted with no smileys

Lastly, check me @ www.sayitafrica.com
Re: Brain Teaser: Recursive Anonymous Function Expression Analysis by AAinEqGuinea: 2:14am On Oct 27, 2018
Foreach cool keep it up Bro cool

(1) (Reply)

Top 10 Things A Web Developer Should Know / What's All The Hype About Windows Server 2012 R2 / I Need A Customized Automated Traffic Bot With My Specification

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 25
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.