Advertisement
MrPolywhirl

URLSearchParams Vanilla vs Lodash

Jul 22nd, 2022
1,173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* ========== Vanilla JS ========== */
  2.  
  3. const applyValue = (existing, newValue) =>
  4.   !existing
  5.     ? newValue
  6.     : !Array.isArray(existing)
  7.       ? [existing, newValue]
  8.       : [...existing, newValue];
  9.  
  10. const paramsToObject = (params) => {
  11.   const res = {};
  12.   for (const [name, val] of searchParams) {
  13.     Object.assign(res, {
  14.       [name]: applyValue(res[name], val)
  15.     });
  16.   }
  17.   return res;
  18. };
  19.  
  20. const search = '?day=Friday&item=Eat&item=Sleep';
  21. const searchParams = new URLSearchParams(search);
  22. console.log(paramsToObject(searchParams));
  23.  
  24. /* ========== Lodash ========== */
  25.  
  26. const { assign, isArray, reduce } = _;
  27.  
  28. const applyValue = (existing, newValue) =>
  29.   !existing
  30.     ? newValue
  31.     : !isArray(existing)
  32.       ? [existing, newValue]
  33.       : [...existing, newValue];
  34.  
  35. const paramsToObject = (params) =>
  36.   reduce([...searchParams.entries()], (res, [name, val]) =>
  37.     assign(res, { [name]: applyValue(res[name], val) }), {});
  38.  
  39. const search = '?day=Friday&item=Eat&item=Sleep';
  40. const searchParams = new URLSearchParams(search);
  41. console.log(paramsToObject(searchParams));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement