This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Listified Tokens, or Somebody’s JavaScript Homework


A pal requested me how I would resolve following drawback:

Given a string within the type "(1, 2, 3), (4, 5, 6), (7, 8, 9)", convert it to a multidimensional array of the shape [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

For my first move, I did some enjoyable shenanigans with Array.prototype.scale back() and a few common expressions like this…

const listified = `(1, 2, 3), (4, 5, 6), (7, 8, 9), (5, junk, 100, 2eggs)`
    .match(/((.*?))/g)
  .scale back(
    (a, c) => [
      ...a,
      [
        ...c
          .match(/([0-9]+)(?=[ ,)])/g)
          .map((el) => !isNaN(el) && parseInt(el)),
      ],
    ],
    []
  );

console.log(listified);
Enter fullscreen mode

Exit fullscreen mode

Demo on Replit.

Whereas it appears to be like cool and looking out cool is my favourite factor about trendy JavaScript, this method does have one thing of an issue for calling loops inside loops, so here’s a extra environment friendly method that walks a pointer throughout the string and gathers up the numbers it finds into work units…

// Convert strings of the shape `"(1, 2, 3), (4, 5, 6), (7, 8, 9)"` into
// multidimensional arrays of the shape `[[1, 2, 3], [4, 5, 6], [7,8,9]]`.

const listifiedTokens = (str) => {
  let knowledge = [];
  let ws = [];
  let x;

  for (c of str) {
    // Taking pains to stop type-coercsion.
    if (!isNaN(c)) {
      x = x ? `${x}${c}` : c;
    }

    // Begin a brand new work set and overwrite
    // any current work set.
    if (c === "(") {
      ws = [];
    }

    // ')' and ',' terminate an inventory entry,
    // and x have to be a quantity earlier than we parse.
    if ([")", ","].contains(c) && !isNaN(x)) {
      ws = [...ws, parseInt(x, 10)];
    }

    // Report the work set.
    if (c === ")") {
      knowledge = [...data, ws];
    }

    // Each time c is NaN, we flush x
    // as a result of this solely occurs on the finish
    // of a sound record or when the record merchandise
    // incorporates an unsupported worth.
    if (isNaN(c)) {
      x = undefined;
    }
  }

  return knowledge;
};

const str = `(1, 2, 3), (4, 5, 6), (7, 8, 8, 9), (100, 2egg, 5, bananas)`;

console.log(listifiedTokens(str));
Enter fullscreen mode

Exit fullscreen mode

Demo on Replit.

It is not almost as cool trying, but it surely’s most likely higher in the long term.

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?