DEV Community

Discussion on: Multiply a string? 🤔

Collapse
peerreynders profile image
peerreynders • Edited
let result;

result = Array.from({ length: 2 }, (_v) => 'Hello world'); // "Hello world" * 2
log();                                                     // ["Hello world", "Hello world"]
result = 'Hello world'.slice(0, -3);                       // "Hello world" - 3
log();                                                     // "Hello wo"
result = chunk('Hello world', 3);                          // "Hello world" / 3
log();                                                     // ["Hel", "lo ", "wor", "ld"]

function chunk(s, size) {
  const length = Math.ceil(s.length / size);
  const toChunk = (_v, i) => {
    const start = i * size;
    return s.slice(start, start + size);
  };
  return Array.from({ length }, toChunk);
}

function log() {
  console.log(result);
}
Enter fullscreen mode Exit fullscreen mode

So while the operator versions have brevity on their side I think they lack clarity, especially for those who are encountering this type of usage for the very first time. And in JavaScript the operators don't fit with the way type coercion is designed to work.

The solution to many problems is simply:

Just write a function

On a personal level I've never understood Haskell's obsession with "operators". "operators" don't add anything if they do exactly the same work as a function with one or two arguments - i.e. just stick to a function. The case is different if and only if not all arguments of the operator expression are evaluated, e.g. the conditional operator.

In many ways I prefer Erlang's philosophy:

This adheres to our general principle - we do not provide built-in mechanisms, we provide primitives with which mechanisms can be built

(Erlang provides the primitives, OTP implements the mechanisms)

i.e. let the language only supply the essential functionality needed to build everything else.

In the case of JavaScript it's a bit different as you are trying to delegate as much work as possible to the browser - the runtime can accomplish many natively implemented tasks much faster.

Collapse
adam_cyclones profile image
Adam Crockett Author

So before I start:

result = Array.from({ length: 2 }, (_v) => 'Hello world');

The callback is actually slower then map new Array(n). Completely irrelevant off topic stuff right here 😂

I take the point 💯 functional is clear and my thoughts ... Are usually a jumbled mess, non the less apparently Python can multiply a string so it must be a good idea, right? 🤷‍♂️