Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | 10x 12x 13x 11x 13x 11x 11x 15x 11x 1x 11x 11x 13x 1x 1x 1x 1x 2x 1x 1x | import { defaults } from "./defaults";
import { presets } from "./presets";
import validate, * as validators from "./helpers/validators/index";
import format, * as formatters from "./helpers/formatters/index";
import { getRandomChars } from "./helpers/utils/index";
class Shortener {
constructor({
target,
length = defaults.length,
alphabet = defaults.alphabet,
} = {}) {
this.setConfiguration({ target, length, alphabet });
}
get target() {
return this._target;
}
set target(target) {
validate(validators.target, target);
this._target = target;
}
get length() {
return this._length;
}
set length(length) {
validate(validators.length, length);
this._length = length;
}
get alphabet() {
return this._alphabet;
}
set alphabet(alphabet) {
// check if alphabet is set to a preset
if (presets[alphabet]) {
alphabet = presets[alphabet];
}
validate(validators.alphabet, alphabet);
this._alphabet = alphabet;
}
/**
* apply all configuration params to the current instance
* @param {object} target
* @param {number} length
* @param {string} alphabet
*/
setConfiguration({
target,
length = defaults.length,
alphabet = defaults.alphabet,
} = {}) {
Object.assign(this, { target, length, alphabet });
}
/**
* Gets information about the current configuration
*/
getInfo() {
const config = {
target: this.target,
length: this.length,
alphabet: this.alphabet,
};
const possibilities = Math.pow(this.alphabet.length, this.length);
const probability = 1 / possibilities;
return {
config,
collisionInfo: {
possibilities,
probability,
},
};
}
/**
* Shortens a given url with the current configuration of the shortener
* @param {string} url
*/
shorten(url) {
validate(validators.url, url);
const id = getRandomChars(this.length, this.alphabet);
return {
id,
original: url,
target: format(
formatters.target,
format(formatters.trimSlashes, this.target),
id
),
};
}
}
export { Shortener };
|