UNPKG

asksuite-core

Version:
80 lines (62 loc) 1.83 kB
const defaultDictionary = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; const regex = '(?:^|\\s)#([a-zA-Z0-9]+(?:-?[a-zA-Z0-9]+))(?:$|\\s)'; module.exports = (dictionary = defaultDictionary) => { const encode = value => { if (!Number.isInteger(value)) { return null; } const result = []; let remainder = value; do { const index = remainder % dictionary.length; remainder = Math.floor(remainder / dictionary.length); result.unshift(dictionary.charAt(index)); } while (remainder > 0); return result.join(''); }; const decode = value => { if (!validate(value)) { return null; } value = String(value); let result = 0; for (let i = 0; i < value.length; i++) { const index = dictionary.indexOf(value.charAt(value.length - i - 1)); result += index * Math.pow(dictionary.length, i); } return result; }; const validate = value => { if (value !== 0 && !value) { return false; } if (Number.isInteger(value)) { return true; } for (let i = 0; i < value.length; i++) { if (dictionary.indexOf(value.charAt(i)) === -1) { return false; } } return true; }; const extract = value => { const result = value.match(new RegExp(regex)); if (!result || !result[1]) return null; const resultWithoutHash = result[1]; const [encodedValue1, encodedValue2] = resultWithoutHash.indexOf('-') >= 0 ? resultWithoutHash.split('-') : [resultWithoutHash, '']; if (validate(encodedValue1)) { if (encodedValue2.length && validate(encodedValue2)) return `${encodedValue1}-${encodedValue2}`; return encodedValue1; } return null; }; return { encode, decode, validate, extract, }; };