runjs.co Open in urlscan Pro
49.12.104.113  Public Scan

URL: https://runjs.co/s/Ap9B$KL@c
Submission: On November 22 via manual from US — Scanned from DE

Form analysis 0 forms found in the DOM

Text Content

run{JS}


JAVASCRIPT PLAYGROUND



run{JS}
newsharecopy
New Code
Select Language
JavaScriptTypeScript {}
NEXTCancel
Code Template
Hello World Empty console.log
CREATECancel
Share Code with Link




xxxxxxxxxx



 

/* the purpose of this snippet is to take text formatted in a specific way (as invoice line item description) and parse it for the information we require */

// setup regex patterns

const supplierCodeItemCodeItemDescPattern = /([\w]+)[\s]*([\w]+)[\s]*(.*)/;

const sizeAndQuantityPattern = /^([^-\s]+)[\s]*[-]{1}[\s]*([\d]+)[\n]?/m;

// string to test with as example line item text

const testString = `FB Z990 HiVis Two Tone Open Front Shirt

Yellow/Navy

- V/C logo on LHC

Sizes:

M-5 (testing standard format)

S/M - 10 - Josh (testing standard format with individual name after, with the use of a forward slash combination size delimiter)

L/XL -     15 (testing silly amount of spacing)

L22-56 (testing alphanumeric size)`;

console.log(`Test String:`, testString);

// split string into individual lines

const testStringLines = testString.split('\n');

// init vars

let supplierCode = null, itemCode = null, itemDescription = null, itemColourway = null;

const sizesAndQuantities = [];

let sizesIndicatorFound = false;

// loop through lines sequentially

for (let lineIndex = 0; lineIndex < testStringLines.length; lineIndex++) {

  // store line contents in var for ease of reference

  const lineContents = testStringLines[lineIndex];

  console.log(`Line #${lineIndex + 1} - Contents: "${lineContents}"`);

  switch (lineIndex) {

    // first line should always be in the format `[supplierCode] [itemCode] [itemDescription]`

    case 0:

      // test line contents against regex pattern

      if (supplierCodeItemCodeItemDescPattern.test(lineContents)) {

        // match successful, go ahead and extract capture groups data

        console.log(`First Line Passed!`, lineContents);

        const firstLineMatches = lineContents.match(supplierCodeItemCodeItemDescPattern);

        console.log(firstLineMatches);

        // set vars from captured data

        supplierCode = firstLineMatches[1];

        itemCode = firstLineMatches[2];

        itemDescription = firstLineMatches[3];

      }

      else {

        console.error(`First Line Failed!`, lineContents);

      }

      break;

    // second line should always be the colour of the item so we can just straight copy that rather than wasting resources on a regex pattern test and matching

    case 1:

      itemColourway = lineContents;

      break;

    // the following code will execute if the line # is anything other than 1 or 2 (0 - 1)

    default:

      // check if the sizes indicator has been found (string literal of 'size:' or 'sizes:' on one line

      // if found, update the bool to indicate this and continue looping

      // if not found, we just ignore this line's contents and continue looping until it is found

      if (lineContents.toLowerCase() == 'size:' || lineContents.toLowerCase() == 'sizes:') {

        sizesIndicatorFound = true;

        console.log(`Sizes Indicator Found!`);

      }

      // sizes indicator has been found, we should be safe now to pattern match all remaining lines for size and quantity

      else if (sizesIndicatorFound) {

        // test pattern against line contents

        if (sizeAndQuantityPattern.test(lineContents)) {

        // match successful, go ahead and extract capture groups data

          console.log(`Size & Quantity Check passed!`, lineContents);

          const sizeAndQuantityMatches = lineContents.match(sizeAndQuantityPattern);

          console.log(sizeAndQuantityMatches);

          // set vars from captured data (store an object for each size/qty pair in an array)

          sizesAndQuantities.push({

            size: sizeAndQuantityMatches[1],

            qty: parseInt(sizeAndQuantityMatches[2], 10),

          });

        }

      }

      break;

  }

}

// create a line item object with the data we've extracted from the text

const lineItemObj = {

  supplierCode: supplierCode,

  itemCode: itemCode,

  itemDescription: itemDescription,

  itemColourway: itemColourway,

  sizesAndQuantities: sizesAndQuantities,

};

console.log(lineItemObj);



Run ÈË
Show Console
Show Editor



JAVASCRIPT CODE EXAMPLES

15 examples

Categories Tags All

One line arrow function

COPY

// One line arrow functions

const multiply = (x, y) => x*y;
console.log(multiply(10, 3));

Arrow are a function shorthand using the "=>" syntax. Arrow functions make code
cleaner, and simplify function scoping and the this keyword.

No parameters arrow function

COPY

// No parameters arrow function

const sayHello = () => console.log('hello world');
sayHello();

No Parameters, parentheses are required when no parameters are present.

Self invoked arrow function

COPY

// Self invoked arrow function

(() => console.log('hi'))(); 


Immediately invoked arrow function expression

Expression bodies

COPY

// Expression bodies

let numbers = [2,4,6,7,8,10,12,15,17,23,44];
let odds = numbers.filter(a => a % 2 !== 0);
let even = numbers.filter(a => a % 2 == 0); 
let numsadd = numbers.map((a, i) => a + i);
let max = (a, b) => a > b ? a : b;
let sum = numbers.reduce((a, b) => a + b); 
let double = numbers.map(n => n * 2);     

console.log(`odds: ${odds}`);
console.log(`even: ${even}`);
console.log(`numsadd: ${numsadd}`);
console.log(`max 19 or 22: ${max(19,22)}`);
console.log(`sum: ${sum}`);
console.log(`double: ${double}`);

Expression bodies

Statement bodies

COPY

// Statement bodies

const numbers = [2,4,6,7,8,10,12,15,17,23,44];
const fives = [];
const numsadd = numbers.map((a, i) => a + i);

numsadd.forEach(v => {
  if (v % 5 === 0) fives.push(v);
});

console.log(`fives: ${fives}`);

Statement bodies

Object Literal Syntax

COPY

// Object Literal Syntax

const setName = (id, name) => ({ id: id, name: name });  
console.log(setName(4, "Joe"));


Arrow functions, like function expressions, can be used to return an object
literal expression

Arrow function, no 'this' binding

COPY

// Arrow function, no 'this' binding

const Person = {
  name: 'Joe',
  hobbies: ['hockey', 'movies', 'fishing'],
  sayHobbies() {
    // The 'this' is relative to the Person
    this.hobbies.map(hobby => console.log(`${this.name} likes to do ${hobby}.`));
  }
};

Person.sayHobbies();


Arrow function has no binding of 'this'

Deep arrow functions

COPY

// Deep arrow functions visually easier to read

setTimeout( () => {
  console.log('I happen sooner');
  setTimeout( () => {
    // deeper code
    console.log('I happen later');
  }, 2000);
}, 1000);

Deep arrow functions visually easier to read

Object destructuring

COPY

// Object destructuring

const colors = { black: '#000000', white: '#FFFFFF' };
const { black, white } = colors;

console.log(black);
console.log(white);

const { A } = { A: 7, B: 20 };
// expected A === 7
console.re.test(A === 7);

const { A: aaa } =  { A: 7, B: 20 };
// expected aaa === 7
console.re.test(aaa === 7);


Destructuring assignment syntax is a JavaScript expression that makes it
possible to unpack values from arrays, or properties from objects, into distinct
variables.

Array destructuring

COPY

// Array destructuring

const arr = ['red', 'green', 'blue'];

for (const [index, value] of arr.entries()) {
  console.log(`Index ${index} -> ${value}`);
}

const [first, second] = arr;

console.re.test(first === 'red');
console.re.test(second === 'green');

Destructuring assignment syntax is a JavaScript expression that makes it
possible to unpack values from arrays, or properties from objects, into distinct
variables.

Array destructuring to swap values

COPY

// Use destructuring to swap values

let a = 1, b = 2;
[b, a] = [a, b];

console.log(a, b); 
// expected 2 1



Using of destructuring assignment to swap array values

Destructuring from functions

COPY

// Destructuring from functions

const foo = () => [1, 2, 3];
const [c, d] = foo();

console.log(c, d); 
// expected 1 2

Destructuring from functions, only select from pattern

Default parameters

COPY

// Default parameters

const Person = (name = "Me", age = 25) => {
  console.log(`${name} is ${age} years old.`);
}

Person();
// expected: Me is 25 years old.

Person("John");
// expected: John is 25 years old.

Person("Suzy", 32);
// expected: Suzy is 32 years old.


Default function parameters allow parameters to be initialized with default
values if no value or undefined is passed.

Parameters with default value assignment

COPY

// Destructured parameter with default value assignment

const f = ([x, y] = [1, 2], {z: z} = {z: 3}) => x + y + z; 

console.log(f()); 
// expected 6

const f2 = ({a = "foo", b = "bar"} = {}) => console.log(a + " " + b);

f2()
// expected 'foo bar'

f2({a: "bar", b: "foo"})
// expected 'bar foo'

Destructured parameter with default value assignment

Computed property keys

COPY

// Computed property keys

const a = 'y';
const context = 'z';
const b = {
  x: 1,
  [a] : 2,
  ...(context && { [context]: 123})
};

console.log(b);

Computed property keys with optional, conditional key

 

©2023 RunJS powered by Remote JavaScript Development Console.Re
To Top