2

How could I chain helper methods in React?

I have a helper.js file with helper functions.

ie: (ps: bellow are just mundane methods to illustrate my issue for now)

//helper.js

export function handleLog(arg) {
  return console.log(`App current state is: ${arg}`);
}

export function handleSlice(arr) {
  return arr.slice(1, 2);
}

export function handleShuffle(arr) {
  return arr.sort(() => Math.random() - 0.5);
}

I'm able to apply the methods to my React app as:

import { handleLog, handleSlice, handleShuffle } from "./helpers";
...

class Heros extends PureComponent {
  constructor() {
    super();
    this.state = {
      heros: ["Hulk", "Thor", "Aquaman", "Stan Lee"]
    };
  }

  render() {
    const { heros } = this.state;
    const shuffledheros = handleShuffle(heros);
    const strongestHero = handleSlice(shuffledheros);
    handleLog(heros);

    /* How could I chain 👇 */
    // const strongestHero = handleShuffle(heros).handleSlice(heros);

    return (
      <>
        <h1>Chained Helpers</h1>
        Strongest: {strongestHero}
      </>
    );
  }
} 

How could I chain ie: handleShuffle(heros).handleSlice(heros) and so on?

  • When chaining the second method it throws: (0 , _helpers.handleSlice)(...).handleSlice is not a function

I've unsuccessfully attempted refactoring the helpers to:

const helpers = {
 f1() { ...do something...; return this;},
 f2() { ...do something...; return this;}
}
export default helpers

That didn't work either. Here is the full code

3 Answers 3

2

You could create a custom class which can hold an array as an internal property to achieve this:

class arrayUtils {
  constructor(items = []) {
    this._data = items;
  }
  reverseIt() {
    this._data.sort((a, b) => b - a)
    return this
  }
  getfirstTwo() {
    this._data.splice(0, 2)
    return this
  }
  printIt() {
    console.log('printing:', this._data)
    return this
  }
  get value() {
    return this._data
  }
}

// Create the instance
var arr = new arrayUtils([1, 2, 3, 4, 5])

// Chain subsequent calls (since we return `this`)
console.log('chain:', arr.reverseIt().printIt().getfirstTwo().printIt())

// get the value
console.log('value:', arr.value)

You can see it working here

Specifically to React you can have this in a separate class in a separate util file and simply export default it:

class helpers ...

export default helpers

then import and create an instance:

import helper from './helper';

// Create the instance
var arr = new helper([1, 2, 3, 4, 5])
Sign up to request clarification or add additional context in comments.

3 Comments

Could you pls show me how this approach would be wired to React?
Sure see the attached link to the answer.
Thank you! This is interesting and a brand new territory to me. I'm still raw on OOP paradigms.
1

First: Array.sort doesn't return any array.

You should rewrite your function handleShuffle

export function handleShuffle(arr) {
  return arr.concat().sort(() => Math.random() - 0.5);
}

Second: you try to call array functions, but Array doesn't contain any handleShuffle or handleSplice functions. So you should run function by function:

const strongestHero = handleShuffle(handleSlice(heros));

Your forked example

11 Comments

The provided fork does not execute handleShuffle only handleSlice. I'm also confused about why the need for concat ? My shuffling method is working I just can't chain them together.
we need concat because sort function is not return anything. I gived link for explanation
handleShuffle(handleSlice(heros)); I executed two function step by step
the issue is that your suggestion isn't shuffling the array. It only returns the same value on each page reload.
Because I'm slice array first and shuffle array with 1 element
|
0

Another solution: create Array prototype's methods:

Array.prototype.handleSlice = function() {
    return this.slice(1, 2);
};

Array.prototype.handleShuffle = function() {
    return this.concat().sort(() => Math.random() - 0.5);
};

So you can execute your methods as cascade.

heros.handleShuffle().handleSlice();

But I'm think that Array extending for those simple functions is not best idea.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.