فهرست منبع

16 All your base.

Frédéric G. MARAND 5 ماه پیش
والد
کامیت
42cb3401a2

+ 13 - 0
all-your-base/.eslintignore

@@ -0,0 +1,13 @@
+!.meta
+
+# Protected or generated
+.git
+.vscode
+
+# When using npm
+node_modules/*
+
+# Configuration files
+.eslintrc.cjs
+babel.config.cjs
+jest.config.cjs

+ 38 - 0
all-your-base/.eslintrc.cjs

@@ -0,0 +1,38 @@
+module.exports = {
+  root: true,
+  parserOptions: {
+    tsconfigRootDir: __dirname,
+    project: ['./tsconfig.json'],
+  },
+  overrides: [
+    // Student provided files
+    {
+      files: ['*.ts'],
+      excludedFiles: ['.meta/proof.ci.ts', '.meta/exemplar.ts', '*.test.ts'],
+      extends: '@exercism/eslint-config-typescript',
+    },
+    // Exercism given tests
+    {
+      files: ['*.test.ts'],
+      excludedFiles: ['custom.test.ts'],
+      env: {
+        jest: true,
+      },
+      extends: '@exercism/eslint-config-typescript/maintainers',
+    },
+    // Student provided tests
+    {
+      files: ['custom.test.ts'],
+      env: {
+        jest: true,
+      },
+      extends: '@exercism/eslint-config-typescript',
+    },
+    // Exercism provided files
+    {
+      files: ['.meta/proof.ci.ts', '.meta/exemplar.ts', '*.test.ts'],
+      excludedFiles: ['custom.test.ts'],
+      extends: '@exercism/eslint-config-typescript/maintainers',
+    },
+  ],
+}

+ 21 - 0
all-your-base/.exercism/config.json

@@ -0,0 +1,21 @@
+{
+  "authors": [
+    "CRivasGomez"
+  ],
+  "contributors": [
+    "masters3d",
+    "SleeplessByte"
+  ],
+  "files": {
+    "solution": [
+      "all-your-base.ts"
+    ],
+    "test": [
+      "all-your-base.test.ts"
+    ],
+    "example": [
+      ".meta/proof.ci.ts"
+    ]
+  },
+  "blurb": "Convert a number, represented as a sequence of digits in one base, to any other base."
+}

+ 1 - 0
all-your-base/.exercism/metadata.json

@@ -0,0 +1 @@
+{"track":"typescript","exercise":"all-your-base","id":"ffb727ae043b4f9baaa72ed26e54792a","url":"https://exercism.org/tracks/typescript/exercises/all-your-base","handle":"Fairgame","is_requester":true,"auto_approve":false}

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 3 - 0
all-your-base/.yarn/releases/yarn-3.6.4.cjs


+ 45 - 0
all-your-base/HELP.md

@@ -0,0 +1,45 @@
+# Help
+
+## Running the tests
+
+Execute the tests with:
+
+```bash
+$ yarn test
+```
+
+## Skipped tests
+
+In the test suites all tests but the first have been skipped.
+
+Once you get a test passing, you can enable the next one by changing `xit` to
+`it`.
+
+## Submitting your solution
+
+You can submit your solution using the `exercism submit all-your-base.ts` command.
+This command will upload your solution to the Exercism website and print the solution page's URL.
+
+It's possible to submit an incomplete solution which allows you to:
+
+- See how others have completed the exercise
+- Request help from a mentor
+
+## Need to get help?
+
+If you'd like help solving the exercise, check the following pages:
+
+- The [TypeScript track's documentation](https://exercism.org/docs/tracks/typescript)
+- The [TypeScript track's programming category on the forum](https://forum.exercism.org/c/programming/typescript)
+- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
+- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
+
+Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
+
+To get help if you're having trouble, you can use one of the following resources:
+
+- [TypeScript QuickStart](https://www.typescriptlang.org/docs/handbook/release-notes/overview.html)
+- [ECMAScript 2015 Language Specification](https://www.ecma-international.org/wp-content/uploads/ECMA-262_6th_edition_june_2015.pdf) (pdf)
+- [Mozilla JavaScript Reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference)
+- [/r/typescript](https://www.reddit.com/r/typescript) is the TypeScript subreddit.
+- [StackOverflow](https://stackoverflow.com/questions/tagged/typescript) can be used to search for your problem and see if it has been answered already. You can also ask and answer questions.

+ 53 - 0
all-your-base/README.md

@@ -0,0 +1,53 @@
+# All Your Base
+
+Welcome to All Your Base on Exercism's TypeScript Track.
+If you need help running the tests or submitting your code, check out `HELP.md`.
+
+## Introduction
+
+You've just been hired as professor of mathematics.
+Your first week went well, but something is off in your second week.
+The problem is that every answer given by your students is wrong!
+Luckily, your math skills have allowed you to identify the problem: the student answers _are_ correct, but they're all in base 2 (binary)!
+Amazingly, it turns out that each week, the students use a different base.
+To help you quickly verify the student answers, you'll be building a tool to translate between bases.
+
+## Instructions
+
+Convert a sequence of digits in one base, representing a number, into a sequence of digits in another base, representing the same number.
+
+~~~~exercism/note
+Try to implement the conversion yourself.
+Do not use something else to perform the conversion for you.
+~~~~
+
+## About [Positional Notation][positional-notation]
+
+In positional notation, a number in base **b** can be understood as a linear combination of powers of **b**.
+
+The number 42, _in base 10_, means:
+
+`(4 × 10¹) + (2 × 10⁰)`
+
+The number 101010, _in base 2_, means:
+
+`(1 × 2⁵) + (0 × 2⁴) + (1 × 2³) + (0 × 2²) + (1 × 2¹) + (0 × 2⁰)`
+
+The number 1120, _in base 3_, means:
+
+`(1 × 3³) + (1 × 3²) + (2 × 3¹) + (0 × 3⁰)`
+
+_Yes. Those three numbers above are exactly the same. Congratulations!_
+
+[positional-notation]: https://en.wikipedia.org/wiki/Positional_notation
+
+## Source
+
+### Created by
+
+- @CRivasGomez
+
+### Contributed to by
+
+- @masters3d
+- @SleeplessByte

+ 117 - 0
all-your-base/all-your-base.test.ts

@@ -0,0 +1,117 @@
+import { convert } from './all-your-base'
+xit = it
+describe('Converter', () => {
+  it('single bit one to decimal', () => {
+    expect(convert([1], 2, 10)).toEqual([1])
+  })
+
+  xit('binary to single decimal', () => {
+    expect(convert([1, 0, 1], 2, 10)).toEqual([5])
+  })
+
+  xit('single decimal to binary', () => {
+    expect(convert([5], 10, 2)).toEqual([1, 0, 1])
+  })
+
+  xit('binary to multiple decimal', () => {
+    expect(convert([1, 0, 1, 0, 1, 0], 2, 10)).toEqual([4, 2])
+  })
+
+  xit('decimal to binary', () => {
+    expect(convert([4, 2], 10, 2)).toEqual([1, 0, 1, 0, 1, 0])
+  })
+
+  xit('trinary to hexadecimal', () => {
+    expect(convert([1, 1, 2, 0], 3, 16)).toEqual([2, 10])
+  })
+
+  xit('hexadecimal to trinary', () => {
+    expect(convert([2, 10], 16, 3)).toEqual([1, 1, 2, 0])
+  })
+
+  xit('15-bit integer', () => {
+    expect(convert([3, 46, 60], 97, 73)).toEqual([6, 10, 45])
+  })
+
+  xit('empty list', () => {
+    expect(() => {
+      convert([], 2, 10)
+    }).toThrowError('Input has wrong format')
+  })
+
+  xit('single zero', () => {
+    expect(convert([0], 10, 2)).toEqual([0])
+  })
+
+  xit('multiple zeros', () => {
+    expect(() => {
+      convert([0, 0, 0], 10, 2)
+    }).toThrowError('Input has wrong format')
+  })
+
+  xit('leading zeros', () => {
+    expect(() => {
+      convert([0, 6, 0], 7, 10)
+    }).toThrowError('Input has wrong format')
+  })
+
+  xit('negative digit', () => {
+    expect(() => {
+      convert([1, -1, 1, 0, 1, 0], 2, 10)
+    }).toThrowError('Input has wrong format')
+  })
+
+  xit('invalid positive digit', () => {
+    expect(() => {
+      convert([1, 2, 1, 0, 1, 0], 2, 10)
+    }).toThrowError('Input has wrong format')
+  })
+
+  xit('first base is one', () => {
+    expect(() => {
+      convert([], 1, 10)
+    }).toThrowError('Wrong input base')
+  })
+
+  xit('second base is one', () => {
+    expect(() => {
+      convert([1, 0, 1, 0, 1, 0], 2, 1)
+    }).toThrowError('Wrong output base')
+  })
+
+  xit('first base is zero', () => {
+    expect(() => {
+      convert([], 0, 10)
+    }).toThrowError('Wrong input base')
+  })
+
+  xit('second base is zero', () => {
+    expect(() => {
+      convert([7], 10, 0)
+    }).toThrowError('Wrong output base')
+  })
+
+  xit('first base is negative', () => {
+    expect(() => {
+      convert([1], -2, 10)
+    }).toThrowError('Wrong input base')
+  })
+
+  xit('second base is negative', () => {
+    expect(() => {
+      convert([1], 2, -7)
+    }).toThrowError('Wrong output base')
+  })
+
+  xit('both bases are negative', () => {
+    expect(() => {
+      convert([1], -2, -7)
+    }).toThrowError('Wrong input base')
+  })
+
+  xit('wrong output_base base not integer', () => {
+    expect(() => {
+      convert([0], 3, 2.5)
+    }).toThrowError('Wrong output base')
+  })
+})

+ 48 - 0
all-your-base/all-your-base.ts

@@ -0,0 +1,48 @@
+export function convert(
+    digits: number[],
+    inputBase: number,
+    outputBase: number
+): number[] {
+    if (inputBase < 2) {
+        throw new Error("Wrong input base")
+    }
+    if (outputBase < 2) {
+        throw new Error("Wrong output base")
+    }
+    if (outputBase !== Math.floor(outputBase)) {
+        throw new Error("Wrong output base")
+    }
+    if (inputBase === outputBase) {
+        return digits;
+    }
+    if (digits.length == 0) {
+        throw new Error("Input has wrong format");
+    }
+    if (digits[0] === 0 && digits.length > 1) {
+        throw new Error("Input has wrong format");
+    }
+    let reversed = [...digits];
+    reversed.reverse();
+    let value = 0;
+    let pow = 1;
+
+    for (const digit of reversed) {
+        if (digit < 0 || digit >= inputBase) {
+            throw new Error("Input has wrong format");
+        }
+        value += digit * pow;
+        pow *= inputBase;
+    }
+    reversed = [];
+    let current = value;
+    for (; ;) {
+        reversed.push(current % outputBase);
+        current = Math.floor(current / outputBase);
+        if (current === 0) {
+            break;
+        }
+    }
+    const out = [...reversed];
+    out.reverse();
+    return out;
+}

+ 4 - 0
all-your-base/babel.config.cjs

@@ -0,0 +1,4 @@
+module.exports = {
+  presets: ['@exercism/babel-preset-typescript'],
+  plugins: [],
+}

+ 19 - 0
all-your-base/jest.config.cjs

@@ -0,0 +1,19 @@
+module.exports = {
+  verbose: true,
+  projects: ['<rootDir>'],
+  testMatch: [
+    '**/__tests__/**/*.[jt]s?(x)',
+    '**/test/**/*.[jt]s?(x)',
+    '**/?(*.)+(spec|test).[jt]s?(x)',
+  ],
+  testPathIgnorePatterns: [
+    '/(?:production_)?node_modules/',
+    '.d.ts$',
+    '<rootDir>/test/fixtures',
+    '<rootDir>/test/helpers',
+    '__mocks__',
+  ],
+  transform: {
+    '^.+\\.[jt]sx?$': 'babel-jest',
+  },
+}

+ 32 - 0
all-your-base/package.json

@@ -0,0 +1,32 @@
+{
+  "name": "@exercism/typescript-all-your-base",
+  "version": "1.0.0",
+  "description": "Exercism exercises in Typescript.",
+  "private": true,
+  "repository": {
+    "type": "git",
+    "url": "https://github.com/exercism/typescript"
+  },
+  "type": "module",
+  "engines": {
+    "node": "^18.16.0 || >=20.0.0"
+  },
+  "devDependencies": {
+    "@exercism/babel-preset-typescript": "^0.4.0",
+    "@exercism/eslint-config-typescript": "^0.5.0",
+    "@types/jest": "^29.5.2",
+    "@types/node": "~18.16.16",
+    "babel-jest": "^29.5.0",
+    "core-js": "~3.30.2",
+    "eslint": "^8.42.0",
+    "jest": "^29.5.0",
+    "typescript": "~5.0.4"
+  },
+  "scripts": {
+    "test": "yarn lint:types && jest --no-cache",
+    "lint": "yarn lint:types && yarn lint:ci",
+    "lint:types": "yarn tsc --noEmit -p .",
+    "lint:ci": "eslint . --ext .tsx,.ts"
+  },
+  "packageManager": "yarn@3.6.4"
+}

+ 28 - 0
all-your-base/tsconfig.json

@@ -0,0 +1,28 @@
+{
+  "display": "Configuration for Exercism TypeScript Exercises",
+  "compilerOptions": {
+    // Allows you to use the newest syntax, and have access to console.log
+    // https://www.typescriptlang.org/tsconfig#lib
+    "lib": ["ESNext.Array","ESNEXT", "dom"],
+    // Make sure typescript is configured to output ESM
+    // https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c#how-can-i-make-my-typescript-project-output-esm
+    "module": "ES2020",
+    // Since this project is using babel, TypeScript may target something very
+    // high, and babel will make sure it runs on your local Node version.
+    // https://babeljs.io/docs/en/
+    "target": "ESNext", // ESLint doesn't support this yet: "es2022",
+
+    "strict": true,
+    "esModuleInterop": true,
+    "skipLibCheck": true,
+    "forceConsistentCasingInFileNames": true,
+
+    // Because we'll be using babel: ensure that Babel can safely transpile
+    // files in the TypeScript project.
+    //
+    // https://babeljs.io/docs/en/babel-plugin-transform-typescript/#caveats
+    "isolatedModules": true
+  },
+  "include": ["*.ts", "*.tsx", ".meta/*.ts", ".meta/*.tsx"],
+  "exclude": ["node_modules"]
+}

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است