Skip to content

Instantly share code, notes, and snippets.

@AlcaDesign
Last active February 19, 2016 09:39
Show Gist options
  • Save AlcaDesign/0a760f223bc576f9159b to your computer and use it in GitHub Desktop.
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.
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
@AlcaDesign
Copy link
Author

The result is not evenly spaced out but select from chunks.

If you did compact('1234', 30), you would get the stretched string 111111111122222222223333333334. 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:

compact(input, 1)
"N"
compact(input, 2)
"Nr"
compact(input, 3)
"Ner"
compact(input, 4)
"Nu r"
compact(input, 5)
"N ehr"
compact(input, 10)
"N eul    r"
compact(input, 20)
"N ytiln Iomttluepalr"
compact(input, 400)
"NNNooww,,  tthhhiiss  iiss  aaa  ssttoorryy   aallll  aabbooouutt  hhooww   MMyy  lliiffeee  ggoott  ffllliippppeedd--tttuurrnneedd  uuuppssiiddee   ddoowwnn  AAnnndd  II''dd  llliikkee  ttoo   ttaakkee  aa   mmiinnuuttee   JJuusstt  ssiiitt  rriigghhttt  tthheerree   II''llll  ttteellll  yyoouuu  hhooww  II   bbeeccaammee   tthhee  pprriiinnccee  ooff   aa  ttoowwnn   ccaalllleedd   BBeell  AAiir"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment