Last active
February 19, 2016 09:39
-
-
Save AlcaDesign/0a760f223bc576f9159b to your computer and use it in GitHub Desktop.
Compact (or extract) a string into a different length but it comes out horribly disfigured.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var input = 'Now, this is a story all about how My life got flipped-turned upside down And I\'d like to take a minute Just sit right there I\'ll tell you how I became the prince of a town called Bel Air', | |
endLength = 165; | |
function rangeMap(n, in_min, in_max, out_min, out_max) { | |
return (n - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; | |
} | |
function rangeMapFloor(n, a, b, c, d) { | |
return Math.floor(rangeMap(n, a, b, c, d)); | |
} | |
function compact(input, endLength, trim) { | |
if(typeof input !== 'string') { | |
throw new TypeError('Input ' + input + ' is of type ' + | |
typeof input + ' instead of string'); | |
} | |
else if(trim === undefined || trim) { | |
input = input.trim().replace(/\s+/g, ' '); | |
} | |
if(typeof endLength !== 'number') { | |
throw new TypeError('End length ' + endLength + ' is of type ' + | |
typeof endLength + ' instead of number'); | |
} | |
else if(endLength < 0) { | |
throw new RangeError('End length ' + endLength + ' is less than 0.'); | |
} | |
else if(endLength === 0 || input === '') { | |
return ''; | |
} | |
else if(endLength === 1) { | |
return input[0]; | |
} | |
var output = ''; | |
for(var i = 0; i < endLength; i++) { | |
var index = rangeMapFloor(i, 0, endLength-1, 0, input.length-1), | |
char = input[index]; | |
if(char === undefined) { | |
char = input[0]; | |
} | |
output += char; | |
} | |
return output; | |
} | |
console.log(compact(input, endLength)); | |
// Now, thi is a sory all bout ho My lifegot fliped-turnd upsid down An I'd lie to tae a minue Just it rightthere Ill tell ou how became he prine of a twn calld Bel Ar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The result is not evenly spaced out but select from chunks.
If you did
compact('1234', 30)
, you would get the stretched string111111111122222222223333333334
. The section lengths are 10, 10, 9, and 1. The first and last character always appear until 1, you get just the first letter in that case.Examples: