MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

ID court et convivial pour mongo

Vous essayez de convertir une base 16 (hexadécimale) en base 36 (26 caractères alphabétiques plus 10 chiffres). Un moyen simple pourrait être d'utiliser simplement parseInt pour analyser l'identifiant hexadécimal, puis appelez .toString(36) pour convertir cela en base-36. Ce qui transformerait "507f191e810c19729de860ea" en "VDFGUZEA49X1V50356", réduisant la longueur de 24 à 18 caractères.

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>