DEV Community

Cover image for Challenge: Create a `pad` function without using loops!
Gio
Gio

Posted on

2 1

Challenge: Create a `pad` function without using loops!

Photo Credit: Kylie Fitts / www.kyliefitts.com & https://unsplash.com

In any language, implement a function pad that takes a value and conditionally pads it with n number of padding:

const padded = pad({
  value: 'πŸ‘‹',
  padding: '*',
  requiredLength: 4,
})

console.log(padded) // --> ***πŸ‘‹

//////////
// Case 2: do not pad a value whose length is equal to `requiredLength`
//

const padded = pad({
  value: 'πŸ‘‹πŸ‘‹πŸ‘‹πŸ‘‹',
  padding: '*',
  requiredLength: 4,
})

console.log(padded) // --> πŸ‘‹πŸ‘‹πŸ‘‹πŸ‘‹


//////////
// Case 3: do not overwrite a value that is longer than `requiredLength`
//

const padded = pad({
  value: 'πŸ‘‹πŸ‘‹πŸ‘‹πŸ‘‹πŸ‘‹πŸ‘‹',
  padding: '*',
  requiredLength: 4,
})

console.log(padded) // --> πŸ‘‹πŸ‘‹πŸ‘‹πŸ‘‹πŸ‘‹πŸ‘‹
Enter fullscreen mode Exit fullscreen mode

Submit your solutions down below! πŸ‘‡πŸ‘‡πŸ‘‡

Remember, your solution cannot use any sort of loop construct such as while, do, or for!

WARNING: Here is my solution in typescript.

Heroku

Amplify your impact where it matters most β€” building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay