MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

ID breve e intuitivo per mongo

Stai tentando di convertire una base 16 (esadecimale) in base 36 (26 caratteri alfabetici più 10 numeri). Un modo semplice potrebbe essere usare semplicemente parseInt 's radix per analizzare l'id esadecimale, quindi chiamare .toString(36) per convertirlo in base-36. Il che trasformerebbe "507f191e810c19729de860ea" in "VDFGUZEA49X1V50356", riducendo la lunghezza da 24 a 18 caratteri.

function toBase36(id) {
  var half = Math.floor(id.length / 2);
  var first = id.slice(0, half);
  var second = id.slice(half);
  return parseInt(first, 16).toString(36).toUpperCase()
       + parseInt(second, 16).toString(36).toUpperCase();
}

function toBase36(id) {
  var half = Math.floor(id.length / 2);
  var first = id.slice(0, half);
  var second = id.slice(half);
  return parseInt(first, 16).toString(36).toUpperCase()
       + parseInt(second, 16).toString(36).toUpperCase();
}

// Ignore everything below (for demo only)
function convert(e){ if (e.target.value.length % 2 === 0) base36.value = toBase36(e.target.value) }
var base36 = document.getElementById('base36');
var hex = document.getElementById('hex');
document.getElementById('hex').addEventListener('input', convert, false);
convert({ target: { value: hex.value } });
input { font-family: monospace; width: 15em; }
<input id="hex" value="507f191e810c19729de860ea">
<input id="base36" readonly>