Jump to content

Determine if a string is collapsible: Difference between revisions

JavaScript added
No edit summary
(JavaScript added)
Line 1,546:
old: 16 <<<headmistressship>>>
new: 14 <<<headmistreship>>>
</pre>
 
=={{header|JavaScript}}==
<lang javaScript>
String.prototype.collapse = function() {
let str = this;
for (let i = 0; i < str.length; i++) {
while (str[i] == str[i+1]) str = str.substr(0,i) + str.substr(i+1);
}
return str;
}
 
// testing
let strings = [
'',
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
'..1111111111111111111111111111111111111111111111111111111111111117777888',
`I never give 'em hell, I just tell the truth, and they think it's hell. `,
' --- Harry S Truman '
];
for (let i = 0; i < strings.length; i++) {
let str = strings[i], col = str.collapse();
console.log(`«««${str}»»» (${str.length})`);
console.log(`«««${col}»»» (${col.length})`);
}
</lang>
 
{{out}} <pre>
«««»»» (0)
«««»»» (0)
«««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» (72)
«««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»» (70)
«««..1111111111111111111111111111111111111111111111111111111111111117777888»»» (72)
«««.178»»» (4)
«««I never give 'em hell, I just tell the truth, and they think it's hell. »»» (72)
«««I never give 'em hel, I just tel the truth, and they think it's hel. »»» (69)
««« --- Harry S Truman »»» (72)
««« - Hary S Truman »»» (17)
</pre>
 
Cookies help us deliver our services. By using our services, you agree to our use of cookies.