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.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay