How to implement the union of arrays in a functional way?

I have a function that combines an array of objects with a conditional delimiter.

function getSegmentsLabel(segments) {
    var separator = '-';

    var segmentsLabel = '';
    var nextSeparator = '';
    _.forEach(segments, function(segment) {
        segmentsLabel += nextSeparator + segment.label;
        nextSeparator = segment.separatorUsed ? separator : ' ';
    });
    return segmentsLabel;
}

Customs:

var segments = [
    {label: 'First', separatorUsed: true},
    {label: 'Second', separatorUsed: false},
    {label: 'Third', separatorUsed: true},
    {label: 'Forth', separatorUsed: true}
];

getSegmentsLabel(segments); // Result: "First-Second Third-Forth"

How can one write the above function in a getSegmentsLabelpurely functional way without mutating variables? We can use the lodash functions.

+6
source share
6 answers

You can use a method map()that will return a new array, and then join()to get the string format of this array.

var segments = [
    {label: 'First', separatorUsed: true},
    {label: 'Second', separatorUsed: false},
    {label: 'Third', separatorUsed: true},
    {label: 'Forth', separatorUsed: true}
];

function getSegmentsLabel(segments) {
  return segments.map(function(e, i) {
    return e.label + (i != segments.length - 1 ? (e.separatorUsed ? '-' : ' ') : '')
  }).join('')
}

console.log(getSegmentsLabel(segments));
Run code
+3
source

recursion

map/reduce/join - , - , ,

javascript tho; : ?

var segments = [
  {label: 'First', separatorUsed: true},
  {label: 'Second', separatorUsed: false},
  {label: 'Third', separatorUsed: true},
  {label: 'Forth', separatorUsed: true}
];

const main = ([x,...xs]) =>
  x === undefined
    ? ''
    : xs.length === 0
      ? x.label
      : x.label + (x.separatorUsed ? '-' : ' ') + main (xs)
      
console.log (main (segments))
// First-Second Third-Forth

- - , ,

, - - , , .

, " " , - Text.make Text.concat

,

// type Text :: { text :: String, separator :: String }
const Text =
  {
    // Text.make :: (String × String?) -> Text
    make: (text, separator = '') =>
      ({ type: 'text', text, separator }),
      
    // Text.empty :: Text
    empty: () =>
      Text.make (''),
      
    // Text.isEmpty :: Text -> Boolean
    isEmpty: l =>
      l.text === '',
      
    // Text.concat :: (Text × Text) -> Text
    concat: (x,y) =>
      Text.isEmpty (y)
        ? x
        : Text.make (x.text + x.separator + y.text, y.separator),
    
    // Text.concatAll :: [Text] -> Text
    concatAll: ts =>
      ts.reduce (Text.concat, Text.empty ())  
  }

// main :: [Text] -> String
const main = xs =>
  Text.concatAll (xs) .text
  
// data :: [Text]
const data =
  [ Text.make ('First', '-'), Text.make ('Second', ' '), Text.make ('Third', '-'), Text.make ('Fourth', '-') ]
  
console.log (main (data))
// First-Second Third-Fourth
+4

, , .

const separators = [' ', '', '-'];
var getSegmentsLabel = array => array
        .map(({ label, separatorUsed }, i, a) =>
            label + separators[2 * separatorUsed - (i + 1 === a.length)])
        .join('');

var segments = [{ label: 'First', separatorUsed: true }, { label: 'Second', separatorUsed: false }, { label: 'Third', separatorUsed: true }, { label: 'Forth', separatorUsed: true }];

console.log(getSegmentsLabel(segments));
+1
source

Better to use reduceRightinstead mapin this case:

const segments = [
    {label: 'First',  separatorUsed: true},
    {label: 'Second', separatorUsed: false},
    {label: 'Third',  separatorUsed: true},
    {label: 'Forth',  separatorUsed: true}
];

const getSegmentsLabel = segments =>
    segments.slice(0, -1).reduceRight((segmentsLabel, {label, separatorUsed}) =>
        label + (separatorUsed ? "-" : " ") + segmentsLabel,
    segments[segments.length - 1].label);

console.log(JSON.stringify(getSegmentsLabel(segments)));
Run code

As you can see, iterating over the array from right to left is better.


Here's a more efficient version of the program, although it uses a mutation:

const segments = [
    {label: 'First',  separatorUsed: true},
    {label: 'Second', separatorUsed: false},
    {label: 'Third',  separatorUsed: true},
    {label: 'Forth',  separatorUsed: true}
];

const reduceRight = (xs, step, base) => {
    const x = xs.pop(), result = xs.reduceRight(step, base(x));
    return xs.push(x), result;
};

const getSegmentsLabel = segments =>
    reduceRight(segments, (segmentsLabel, {label, separatorUsed}) =>
        label + (separatorUsed ? "-" : " ") + segmentsLabel,
    ({label}) => label);

console.log(JSON.stringify(getSegmentsLabel(segments)));
Run code

It is not purely functional, but if we consider it reduceRightas a black box, you can define it in a getSegmentsLabelpurely functional way.

+1
source

Here I highlight the functions:

// buildSeparatedStr returns a function that can be used
// in the reducer, employing a template literal as the returned value
const buildSeparatedStr = (sep) => (p, c, i, a) => {
  const separator = !c.separatorUsed || i === a.length - 1 ? ' ' : sep;
  return `${p}${c.label}${separator}`;
}

// Accept an array and the buildSeparatedStr function
const getSegmentsLabel = (arr, fn) => arr.reduce(fn, '');

// Pass in the array, and the buildSeparatedStr function with
// the separator
const str = getSegmentsLabel(segments, buildSeparatedStr('-'));

Demo

0
source

const segments = [
    {label: 'First',  separatorUsed: true},
    {label: 'Second', separatorUsed: false},
    {label: 'Third',  separatorUsed: true},
    {label: 'Forth',  separatorUsed: true}
];

const segmentsLabel = segments.reduce((label, segment, i, arr) => {
    const separator = (i === arr.length - 1) ? '' : (segment.separatorUsed) ? '-' : ' ';
    return label + segment.label + separator;
 }, '');

 console.log(segmentsLabel);
Run code
0
source

All Articles