Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parse smaller #1

Open
milahu opened this issue Mar 3, 2021 · 0 comments
Open

parse smaller #1

milahu opened this issue Mar 3, 2021 · 0 comments

Comments

@milahu
Copy link

milahu commented Mar 3, 2021

feel free to steal my code ; )

var parse = (hashString) => (
  Object.fromEntries(
    hashString.slice(1).split('&')
    .map(keyval => (
      cut = keyval.indexOf('='),
      (cut == -1) ? [keyval, true] : (
        key = keyval.slice(0, cut),
        val = decodeURIComponent(keyval.slice(cut + 1)),
        [key, val]
      )
    ))
    .filter(([key, val]) => Boolean(key))
  )
)

sample

> parse('#&&=ignoreMe&foo=bar&foo2=bar=baz=boo&keyOnly')
{ foo: 'bar', foo2: 'bar=baz=boo', keyOnly: true }
a bit more complex (parse numbers and number arrays)
var parseGet = (typekeys) => {
  typekeys = Object.fromEntries(['number', 'numberArray'].map(type => (
    keys = typekeys[type],
    [type, (Array.isArray(keys) ? new Set(keys) : keys.has ? keys : new Set())]
  )));
  if (Array.isArray(keys.number)) keys.number = new Set(numKeys);
  if (!keys.number || !keys.number.has) keys.number = new Set();
  var parse = (hashString) => (
    Object.fromEntries(
      hashString.slice(1).split('&')
      .map(keyval => (
        cut = keyval.indexOf('='),
        (cut == -1) ? [keyval, true] : (
          key = keyval.slice(0, cut),
          raw = keyval.slice(cut + 1),
          val = (
            typekeys.number.has(key) ? parseFloat(raw) :
            typekeys.numberArray.has(key) ? raw.split(',').map(parseFloat) :
            decodeURIComponent(raw)
          ),
          [key, val]
        )
      ))
      .filter(([key, val]) => Boolean(key))
    )
  );
  return parse;
}

var parse = parseGet(); // default parser

var parse = parseGet({ number: ['num1', 'num2'], numberArray: ['numarr1', 'numarr2'] });

parse('#&&=ignoreMe&foo=bar&foo2=bar=baz=boo&keyOnly&num1=1234.5678&numarr1=1.0,2,3,4.567')
var res = {
  foo: 'bar',
  foo2: 'bar=baz=boo',
  keyOnly: true,
  num1: 1234.5678,
  numarr1: [ 1, 2, 3, 4.567 ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant