pallavi kurhade
pallavi kurhade

Reputation: 1

Passing an array to callback

how would you solve this: Update the transform function such that it works with n number elements and also same function works for string element ?

const input = [
[2,3,5],
[2,4],
[7,8,9]
];

/*Edit only the transform */

const transform = (input, callback) => {
return callback([input[0],input[1]]);
}

/*Edit code only above */
   

const output = transform(input, (elm1, elm2) => {
return elm1.concat(elm2);// should return [7,8,9,2,4,2,3,5]
});

const input2 = ["hello", "welcome", !];

const output2 = transform(input2, (elm) => {
return elm.toUppercase(); // should return HELLO WELCOME !
});

Thank you all

Upvotes: 0

Views: 635

Answers (2)

David Bell
David Bell

Reputation: 505

In my opinion you're not writing clear JavaScript code. Functional paradigms are your friend but units of work that aren't meaningful will only work against you. What benefit does your transform function provide, why is it better than calling the cb method directly on your data? Consider looking into es6 array functions like flatMap and reduce.

const input = [
    [2,3,5],
    [2,4],
    [7,8,9]
]

console.log(input.reduceRight((acc,cur) => acc.concat(cur), []))
// [7, 8, 9, 2, 4, 2, 3, 5]

console.log(["hello", "world"].map(str => str.toUpperCase()).join(" "))
//"HELLO WORLD"

Upvotes: 1

AdriSolid
AdriSolid

Reputation: 2825

You would need to pass the whole array to your transform function.

  • For the first output => flat the arrays using flat(Infinity)

  • For the second output => 'merge' all array value using join and then apply toUpperCase to the whole string:

const input = [
  [2,3,5],
  [2,4],
  [7,8,9]
];

const transform = (input, callback) => {
  return callback(input);
}

const output = transform(input.reverse(), (elm1, elm2) => {
  return elm1.concat(elm2); // should return [7,8,9,2,4,2,3,5]
});

console.log(output.flat(Infinity).filter(Boolean));

const input2 = ["hello", " welcome", " !"];

const output2 = transform(input2, (elm) => {
  return elm.join('').toUpperCase(); // should return HELLO WELCOME !
});

console.log(output2);

Upvotes: 0

Related Questions