Home > Blockchain >  problem with reduce and memoisation in javascript hardstructure
problem with reduce and memoisation in javascript hardstructure

Time:05-17

i have to do a task, where i need to iterate over hardstructure with nested functions arrays objects and other data types. get all the numbers there are in string or not in string into the array and then with reduce method i need to calculate their sum, after calculating their sum i need to do memoisation on this function. but something doesnt work with my reduce even though i have written the most simple task there is, calculating the sum of numbers. my reduce doesnt really calculate the right way it skips some parts of the structure and doesnt gather all of the nubmers also it doesnt really calculate right i think

const ex1 = () => ({ a: 13 });
const ex2 = () => [1, 2, 3, 4, 5, "a,,,,,,", 2, 2, 2];
const ex3 = () => [...ex2()];
const ex4 = new Set([1, 2, 3, 4]);

const hardStructure = [
  {
    a: 1,
    b: "2",
    c: [
      {
        a: "123",
        b: "@333z$34",
        c: "122,333,4444,5555",
        z: ex4,
        d: [
          [
            123,
            1,
            "1111",
            23323,
            1222,
            55,
            [1212, 1212, 1212],
            {
              a: 111,
              b: null,
              c: () => 111,
              d: 22,
              e: "e",
              f: () => "fffqqq",
            },
          ],
          [
            2212,
            1,
            "111211",
            23,
            121,
            22,
            [33, 3, 3],
            {
              a: 3,
              b: null,
              c: () => 11221,
              d: 2112,
              e: "e11",
              f: () => "fffqqq",
              g: 2,
            },
          ],
          [
            11,
            22,
            "dsds",
            {
              a: {
                b: {
                  c: {
                    d: {
                      a: 1,
                      b: [ex1()],
                      c: {
                        a: {
                          b: {
                            c: {
                              d: {
                                a: new Map([
                                  ["a2134", 2123123],
                                  ["b", 3],
                                  ["c", 3],
                                ]),
                                b: ex2,
                                c: [...ex3(), "1", 1],
                              },
                            },
                          },
                        },
                      },
                    },
                  },
                },
              },
            },
          ],
        ],
      },
    ],
  },
  {
    d: [
      [
        123,
        1,
        "1111",
        23323,
        1222,
        55,
        [121322332, 12132322, 12323212],
        {
          a: 111,
          b: null,
          c: () => 1123231,
          d: 22,
          e: "e",
          f: () => "fffqqq",
        },
      ],
      [
        2212,
        1,
        "111211",
        23,
        121,
        22,
        [33, 3, 3],
        {
          a: 3,
          b: null,
          c: () => 1123221,
          d: 211,
          e: "e1231",
          f: () => "fffqq1232312123q",
          g: 2123,
        },
      ],
      [
        11,
        22,
        "dsds",
        {
          a: {
            b: {
              c: {
                d: {
                  a: 1,
                  b: [ex1()],
                  c: {
                    a: {
                      b: {
                        c: {
                          d: {
                            a: new Map([
                              [true, 222312],
                              [2, 322],
                              ["c2", 32],
                              [() => {}, 32],
                            ]),
                            b: ex2,
                            c: [...ex3(), "1121123", 1],
                          },
                        },
                      },
                    },
                  },
                },
              },
            },
          },
        },
      ],
    ],
  },
  {
    a: {
      b: {
        c: {
          d: {
            a: 112312,
            b: [1],
            c: {
              a: {
                b: {
                  c: {
                    d: {
                      a: "",
                      b: "",
                      c: "",
                      v: "v12312323",
                    },
                  },
                },
              },
            },
          },
        },
      },
    },
  },
];

const numbersArr = [];
const iterate = (hardStructure) => {
  if (hardStructure === null || hardStructure === undefined) {
    return [];
  }
  if (
    hardStructure.constructor === new Set().constructor ||
    hardStructure.constructor === new Map().constructor
  ) {
    console.log("console from map or set");
    hardStructure.forEach((element) => {
      // console.log("123", element);
      return iterate(element);
    });
  }

  if (typeof hardStructure === "function") {
    return iterate(hardStructure());
  }
  if (Array.isArray(hardStructure)) {
    hardStructure.map((items) => {
      return iterate(items);
    });
  }
  if (typeof hardStructure === "object" && !Array.isArray(hardStructure)) {
    for (let key in hardStructure) {
      // console.log(hardStructure[key]);
      return iterate(hardStructure[key]);
    }
  }
  if (typeof hardStructure !== "string") {
    const stringItem = String(hardStructure);
    for (let i = 0; i < stringItem.length; i  ) {
      if (!isNaN( stringItem)) {
        numbersArr.push( stringItem);
      }
    }
  }

  for (let i = 0; i < hardStructure.length; i  ) {
    // console.log(i);
    if (!isNaN( hardStructure[i])) {
      // console.log("12345678910", isNaN( hardStructure[2]));
      numbersArr.push( hardStructure[i]);
    }
  }

  const sumWithInitial = numbersArr.reduce((accumulator, currentValue) => {
    console.log(accumulator,currentValue)
    return accumulator   currentValue;
  },0);

  //  console.log(numbersArr)
  console.log(sumWithInitial);
  return sumWithInitial;
};

iterate(hardStructure);

CodePudding user response:

Your requirements aren't entirely clear, especially as to handling of String and Function properties. This solution assumes that you want to call functions and that you can use parseInt for Strings. If you need to change that, it should be clear enough how and where to do so:

const sumNumbers = (xs) =>
  xs == null
    ? 0
  : xs .constructor == String
    // ? parseInt (xs, 10) || 0 // original version not enough.  Below might not be so either
    ? xs .includes (',') ? sumNumbers (xs .split (',')) : Number (xs .replaceAll (/\D/g, ''))
  : xs .constructor == Number
    ? xs
  : xs .constructor === Array
    ? xs .map (sumNumbers) .reduce ((a, b) => a   b, 0)
  : xs .constructor === Set
    ? sumNumbers ([...xs])
  : xs .constructor === Map
    ? sumNumbers ([...xs .values()])
  : xs .constructor === Function
    ? sumNumbers (xs ()) // or just 0?
  : xs .constructor == Object
    ? sumNumbers (Object .values (xs))
  // TODO: Other types possible here?
    : 0


const ex1 = () => ({a: 13}), 
      ex2 = () => [1, 2, 3, 4, 5, "a,,,,,,", 2, 2, 2], 
      ex3 = () => [...[1, 2, 3, 4, 5, "a,,,,,,", 2, 2, 2]], 
      ex4 = new Set ([1, 2, 3, 4]), 
      hardStructure = [{a: 1, b: "2", c: [{a: "123", b: "@333z$34", c: "122,333,4444,5555", z: ex4, d: [[123, 1, "1111", 23323, 1222, 55, [1212, 1212, 1212], {a: 111, b: null, c: () => 111, d: 22, e: "e", f: () => "fffqqq"}], [2212, 1, "111211", 23, 121, 22, [33, 3, 3], {a: 3, b: null, c: () => 11221, d: 2112, e: "e11", f: () => "fffqqq", g: 2}], [11, 22, "dsds", {a: {b: {c: {d: {a: 1, b: [{a: 13}], c: {a: {b: {c: {d: {a: new Map ([["a2134", 2123123], ["b", 3], ["c", 3]]), b: ex2, c: [...ex3(), "1", 1]}}}}}}}}}}]]}]}, {d: [[123, 1, "1111", 23323, 1222, 55, [121322332, 12132322, 12323212], {a: 111, b: null, c: () => 1123231, d: 22, e: "e", f: () => "fffqqq"}], [2212, 1, "111211", 23, 121, 22, [33, 3 , 3], {a: 3, b: null, c: () => 1123221, d: 211, e: "e1231", f: ()=> "fffqq1232312123q", g: 2123}], [11, 22, "dsds", {a: {b: {c: {d: {a: 1, b: [{a: 13}], c: {a: {b: {c: {d: {a: new Map ([[true, 222312], [2, 322], ["c2", 32], [() => {}, 32]]), b: ex2, c: [...ex3 (), "1121123", 1]}}}}}}}}}}]]}, {a: {b: {c: {d: {a: 112312, b: [1], c: {a: {b: {c: {d: {a: "", b: "", c: "", v: "v12312323"}}}}}}}}}}]

console .log (sumNumbers (hardStructure))

We have four base cases:

  • on a nil value (null or undefined), we return 0
  • on a Number, we return its value
  • on a String, we call parseInt on it and return the value. This is the part I think you would most likely need to change
  • on an unknown type (perhaps a regular expression or a date), we return 0

The others are recursive case:

  • for an Array, we recursively call our function on each element and then total them together.
  • for a Function, we call the function with no arguments, and recur on the result.
  • for our other known types (Object, Set, Map), we extract its values into an Array and recur on the result.
  • Related