Home > Software design >  Recursive solution for an Object in JS
Recursive solution for an Object in JS

Time:09-08

I am solving a kata at codewars. https://www.codewars.com/kata/5540e75396737c4cea000092/train/javascript

I am able to solve the kata but I can't refactor my code for the correct output of function

QUESTİON Description

Find the needle(s) in a haystack by creating a function that returns all properties (recursively) which contains the needle (string).

Return value should be a sorted array.

function search(haystack, needle, arr = []) {
    for (let key in haystack) {
        const keyOne = haystack[key]
        if (typeof keyOne === 'string' && keyOne.indexOf(needle) !== -1) {
            key
            arr.push(keyOne[key]??=key)
        }
        else if (typeof keyOne === 'object' ) {
            search(keyOne, needle, arr)
        }
    }
    return arr
}



const obj = {
    site: "Codewars",
    description: "Lorem ipsum dolor sit...",
    obj2: {
        str: "Yeah, Codewars!",
        num: 123,
        obj3: {
            something: "Ph'nglui mglw'nafh Codewars R'lyeh wgah'nagl fhtagn. Gotha fm'latgh h'gof'nn, geb chtenff"
        }
    }
};

console.log(search(obj, 'Codewars')) //results =[ 'site', 'str', 'something' ]

But my solution must return the output with this exact output

["obj2.obj3.something", "obj2.str", "site"]

So is there an any hint or trick that anybody can you show me to grasp more Js logic ?

CodePudding user response:

This code passes the tests. Thnks to everbody

function search(haystack, needle, arr = [], path = []) {
    for (let key in haystack) {
        const keyOne = haystack[key]
        if (typeof keyOne === 'string' && keyOne.indexOf(needle) !== -1) {
            key
            arr.push(path.join`.`   '.'   key)
        }
        else if (typeof keyOne === 'object' ) {
            search(keyOne, needle, arr, path.concat(key))
        }
    }
    return arr.map(e => e.startsWith('.') ? e.slice(1) : e).sort()
}

const obj = {
    site: "Codewars",
    description: "Lorem ipsum dolor sit...",
    obj2: {
        str: "Yeah, Codewars!",
        num: 123,
        obj3: {
            something: "Ph'nglui mglw'nafh Codewars R'lyeh wgah'nagl fhtagn. Gotha fm'latgh h'gof'nn, geb chtenff"
        }
    }
};

console.log(search(obj, 'Codewars')) // results ==>> [ 'obj2.obj3.something', 'obj2.str', 'site' ]

  • Related