Advertisement
Guest User

Untitled

a guest
Jul 24th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. const l = require('fast-levenshtein');
  2. const has = (o, p) => Object.prototype.hasOwnProperty.call(o, p);
  3.  
  4. function leven(target, list) {
  5. const sorted = [];
  6. for (const item of list) {
  7. const score = l.get(target, item);
  8. sorted.splice(+score - 1, 0, item);
  9. }
  10. let ret;
  11. while ((ret = sorted.shift()) == null) {}
  12. return ret;
  13. }
  14.  
  15. function find(target, prop, value, setting) {
  16. prop = has(target, prop) ? prop : leven(prop, Object.keys(target));
  17. if (setting) return target[prop] = value;
  18. return target[prop];
  19. }
  20.  
  21. const handler = {
  22. get(target, prop) {
  23. const found = find(target, prop);
  24. return typeof found === 'object' ? new Proxy(found, handler) : found;
  25. },
  26. set(target, prop, value) {
  27. const found = find(target, prop, value, true);
  28. return typeof found === 'object' ? new Proxy(found, handler) : found;
  29. },
  30. };
  31.  
  32. function autocorrect(obj) {
  33. return new Proxy(obj, handler);
  34. };
  35.  
  36. if (typeof module !== 'undefined') module.exports = autocorrect;
  37. if (typeof window !== 'undefined') window.objAutocorrect = autocorrect;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement