I'm just getting into functional programming (as in, just started reading the book) and as practice I'm trying to refactor a past answer I wrote to fit in line with the functional style.

The function is intended to be a template literal tag, like so:

let myString = withoutWhitespace`This is a really long string, that needs to wrap over
    several lines. With a normal template literal you can't do that, but you can 
    use a template literal tag to get rid of line breaks and indents.`;

Here's the original:

function withoutWhitespace(strings, ...placeholders) {
  // Build the string as normal, combining all the strings and placeholders:
  let withSpace = strings.reduce((result, string, i) => (result + placeholders[i - 1] + string));
  let withoutSpace = withSpace.replace(/\s\s+/g, ' ');
  return withoutSpace;

And here's my new version:

function withoutWhitespace(strings, ...placeholders) {
  return trimWhitespace(merge(strings, placeholders).join());

function trimWhitespace(input) {
    return input.replace(/\s\s+/g, ' ');

function merge(one, two) {
    let result = [];
    for(let i = 0; i < Math.max(one.length, two.length) - 1; i++) {
        pushIfTruthy(result, one[i]);
        pushIfTruthy(result, two[i]);
    return result;

function pushIfTruthy(array, item) {
    if(item) {
    return array;

How does this look so far? What improvements could I make?

  • \$\begingroup\$ What do you mean by 'so far'? Is there functionality you haven't included yet? \$\endgroup\$ – dfhwze Jun 17 at 15:28
  • \$\begingroup\$ @dfhwze It works as-is; I'm just new to functional programming style and wanted to hear from others on how well this matches that style and what could be improved. \$\endgroup\$ – Ian Jun 17 at 15:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.