0

I define an absorbing String simply as follows: When concatenated with any other String, the result is empty String (another absorbing element).

I know that probably such element doesn't exist natively in JavaScript, but I came up with a simple logic that simulate this

"_".repeat(str.length/str.length)+ str+ "_".repeat(str.length/str.length)

Example:

var str = "HP";
var result = "_".repeat(str.length/str.length)+ str+ "_".repeat(str.length/str.length);
[out]: "_HP_"
str = "";
var result = "_".repeat(str.length/str.length)+ str+ "_".repeat(str.length/str.length);
[out]: ""

The purpose is simply to have underscores besides String only when they exist.

This is very helpful when many String are concatenated with one separator, and that we would like to avoid If Else block-like code.

Is there a shorter form?

15
  • 4
    Please show input and expected output Commented Jun 12, 2018 at 8:45
  • 1
    What should be the reason for str.length/str.length? It's either 1 all the time anyway or results in a "division by zero". Commented Jun 12, 2018 at 8:50
  • Not optimal code but it does the job: "_".repeat(NaN) gives empty String. At least when run on Chrome JS engine V 65.0 Commented Jun 12, 2018 at 8:51
  • 1
    One way to concatenate many strings with one separator while avoiding If Else blocks would be: [str1, str2, str3, ...].filter(str => str).join(SEPARATOR) Commented Jun 12, 2018 at 8:53
  • 3
    @Curcuma_ I think you are not describing your problem in this SO question. You are rather describing your solution approach. If you edit the question and write down your full problem (which led you to needing the concept of an "absorbing" string) we might be able to give you an even better solution. Commented Jun 12, 2018 at 9:00

1 Answer 1

2

You could use a logical AND && wich checks the string for truthyness.

function pad(string) {
    return string && '_' + string + '_';
}

console.log(pad("HP"));
console.log(pad(""));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.