Friday, February 17, 2017

Using Functional Programming to replace elements in an array ...

The following pieces of code produce equivalent results:

var a = ['apple','banana','grapefruit','kiwi','strawberry'];
var b = ['banana','grape','watermelon','tangerene','kiwi'];
var matches = [];

for(var i = 0; i < a.length; i++) {
  for(var j = 0; j < b.length; j++) {
     if(a[i] === b[j]) {       
          matches.push(a[i]);
      }
   }
}

console.log(matches);

>>  ['banana','kiwi']





var _ = require('lodash');
var a = ['apple','banana','grapefruit','kiwi','strawberry'];
var b = ['banana','grape','watermelon','tangerene','kiwi'];
var matches = [];

var g = _.each(a, function(someThing) {
   _.each(b, function(someThingElse) {
       if(someThing === someThingElse) {
          matches.push(someThing);
       }
  })
})

>> ['banana','kiwi']
----------------------------------------
 sidenote: I am trying to embed a string replacement if there is a match:
----------------------------------------

 var a = {'apple' : 'orchard fruit','grape':'fruit of the vine'};
 var b = 'The apple grows right next to the grape';

  var c = Object.keys(a);

 for(var i = 0; i <  c.length; i++) {
      var newb = b.replace(c[i],a[c[i]]);
      var b = new b;
 }

  console.log(b);

>> The orchard fruit grows right next to the fruit of the vine

-     -       -         -          -

var b might be instead:

var b = ['apple','orange','grape','watermelon'];

which when operated on would give:

var b = ['orchard fruit','orange','grape','watermelon'];

I also want a second array that gives what I replaced:

var c = ['apple','grape'];

(the code a the beginning of this post does this...)

------------------------------------------
end sidenote
-----------------------------------------


However, the second piece of code appears to violate the side effects rule of functional programming.

Anjana Vakil discusses this in "Learning Functional Programming with JavaScript - JSUnconf 2016'" (https://www.youtube.com/watch?v=e-5obm1G_FY) .

An article in Smashing Magazine seems the most useful:

https://www.smashingmagazine.com/2014/07/dont-be-scared-of-functional-programming/

also, maybe I should use map at some point? Maybe the function can be the replacing

SeeAlso: https://www.youtube.com/playlist?list=PLQB2www8g0gROTRDOixjquch4w4MZs8OY&spfreload=5

-------------------

Perhaps this will work:

function find(a,b) {
   let dummy = [];
   _.each(a, function(someThing) {
      _.each(b, function(someThingElse) {
          if(someThing === someThingElse) {
             dummy.push(someThing);
          }
       })
   })
   return dummy;
}
 

Push and array declaration is used inside of a function here:
http://cryto.net/~joepie91/blog/2015/05/04/functional-programming-in-javascript-map-filter-reduce/
This is stateless and immutable

No comments:

Post a Comment