calculate.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2017-2019 @polkadot/app-accounts authors & contributors
  2. // This software may be modified and distributed under the terms
  3. // of the Apache-2.0 license. See the LICENSE file for details.
  4. import { GeneratorCalculation, GeneratorOptions } from './types';
  5. const MAX_OFFSET = 5;
  6. function calculateAtOne (atOffset: number, test: string[], address: string): GeneratorCalculation {
  7. return {
  8. count: test.reduce((count, c, index): number => {
  9. if (index === count) {
  10. count += (c === '?' || c === address.charAt(index + atOffset)) ? 1 : 0;
  11. }
  12. return count;
  13. }, 0),
  14. offset: atOffset
  15. };
  16. }
  17. function calculateAt (atOffset: number, test: string[][], address: string): GeneratorCalculation {
  18. let bestCount = 0;
  19. let bestOffset = 1;
  20. for (let i = 0; i < test.length; i++) {
  21. const { count, offset } = calculateAtOne(atOffset, test[i], address);
  22. if (count > bestCount) {
  23. bestCount = count;
  24. bestOffset = offset;
  25. }
  26. }
  27. return {
  28. count: bestCount,
  29. offset: bestOffset
  30. };
  31. }
  32. export default function calculate (test: string[][], _address: string, { atOffset = -1, withCase = false }: GeneratorOptions): GeneratorCalculation {
  33. const address = withCase
  34. ? _address
  35. : _address.toLowerCase();
  36. if (atOffset > 0) {
  37. return calculateAt(atOffset, test, address);
  38. }
  39. let bestCount = 0;
  40. let bestOffset = 1;
  41. for (let index = 0; index < MAX_OFFSET; index++) {
  42. const { count, offset } = calculateAt(index, test, address);
  43. if (count > bestCount) {
  44. bestCount = count;
  45. bestOffset = offset;
  46. }
  47. }
  48. return {
  49. count: bestCount,
  50. offset: bestOffset
  51. };
  52. }