The Challenge
Given a multiline string, return the longest substring of leading whitespace present in every line, ignoring empty lines or lines composed only of whitespace. If input is empty or whitespace, return nullish or the empty string--up to you.
Update: Per Meta consensus, the input may also be treated as an array of strings. My examples below could be shortened by excluding the .split()
calls.
I wrote a quick script for my iPhone that comments or uncomments JavaScript code (since I can't use ctrl+/).
I want the //
placed the furthest right that it can, given that each //
is aligned with the other lines. If a line is only whitespace (or empty), I want to skip adding a comment.
To do this, I must determine the longest leading whitespace substring that exists in every line. So, given the input string
const x = () =>
y.split()
.map(s =>
s.length
)
.join()
console.log(x)
the result of the algorithm would be 2 spaces. (Note: Line 7 has 4 leading spaces, but the browser may or may not remove them. It does not appear to remove them in the example solutions below.) If the input was only lines 3-7, the result would be 6 spaces.
A simple JS solution to achieve this would be
const solution = text => {
const lines = text.split('\n').filter(l => !!l.trim())
let result = ''
while (lines.every(l => l.startsWith(result + ' '))) {
result += ' '
}
return result
}
// test
const text =
` const x = () =>
y.split()
.map(s =>
s.length
)
.join()
console.log(x)`
let result = solution(text);
console.log(`|${result}| ${result.length} spaces`)
const lines3Through7 = text.split('\n').slice(2, 7).join('\n')
result = solution(lines3Through7)
console.log(`|${result}| ${result.length} spaces`)
result = solution(
`abc
def`)
console.log(`|${result}| ${result.length} spaces`)
I'm sure you can do better than this.
Another would be
const solution = text =>
' '.repeat(
text.split('\n')
.filter(l => !!l.trim())
.map(l => l.length - l.trimStart().length)
.reduce((m, v) => Math.min(m, v))
)
// test
const text =
` const x = () =>
y.split()
.map(s =>
s.length
)
.join()
console.log(x)`
let result = solution(text);
console.log(`|${result}| ${result.length} spaces`)
const lines3Through7 = text.split('\n').slice(2, 7).join('\n')
result = solution(lines3Through7)
console.log(`|${result}| ${result.length} spaces`)
result = solution(
`abc
def`)
console.log(`|${result}| ${result.length} spaces`)
Assume all whitespaces are space characters (i.e. not \t
). For input that has no non-whitespace characters, it should return nullish or 0 spaces, up to you.
You can use any language, but I'd also like someone to present an answer in JavaScript ✅.
Shortest answer wins. Include your answer, a prettified version of your answer for readability, and for esoteric languages, an explanation of how your script works.