Different Ways To Get Sh.t Done!(And always bet on Javascript)

And why Javascript is awsome

·

1 min read

Hi Everyone,

This is my first blog post. In this post I want to share some code snippets to make squares of a given number array. We have to realize that there isn't only one true answer in Javascript world. We always have different approaches and methods to do things. As Linus Torvalds says

Talk is cheap(not actually Linus come on buddy ), Show me the code.

function makeSquaresRecursive(numbers: any[]) {
    const result: Array<number> = [];

    numbers.forEach((element: any) => {
        if (typeof element === "number") {
            result.push(element ** 2);
        } else {
            const innerResult = makeSquaresRecursive(element);
            result.push(...innerResult);
        }
    });
    return result;
}

function makeSquaresWithFlatMap(numbers: any[]) : any[] {
    return numbers.flatMap((element: any) => {
        if (typeof element === "number") {
            return element ** 2;
        }
        return makeSquaresWithFlatMap(element);
    });
}

function makeSquaresWithFlatAndMap(numbers: any[]) {
    return numbers.flat(10).map(num => num ** 2)
}

function makeSquaresWithToString(numbers: any[]) {
    return numbers.toString().split(",").map(item => Number(item) ** 2);
}


const nums = [1, 2, [3, 4, [5, 6, [7, [8, 9, [10]]]]]];
// ->  [1,3,9,16,25,36,49,64,81,100]

console.log(makeSquaresRecursive(nums));
console.log(makeSquaresWithFlatMap(nums));
console.log(makeSquaresWithFlatAndMap(nums));
console.log(makeSquaresWithToString(nums));

As you see from above we achieved same results with different methods. Please do not hesitate to share, comment :)

If you interested here is the gist of the above code snippets. Enjoy. gist.github.com/chety/0528eda00106346623a5b..