├── tslint.json ├── src ├── obj-path-proxy.ts └── ts-object-path.ts ├── .gitignore ├── .editorconfig ├── .travis.yml ├── tsconfig.json ├── CONTRIBUTING.md ├── tools ├── gh-pages-publish.ts └── semantic-release-prepare.ts ├── LICENSE ├── rollup.config.ts ├── README.md ├── package.json ├── code-of-conduct.md └── test └── ts-object-path.test.ts /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint-config-standard", 4 | "tslint-config-prettier" 5 | ] 6 | } -------------------------------------------------------------------------------- /src/obj-path-proxy.ts: -------------------------------------------------------------------------------- 1 | 2 | export type ObjPathProxy = { 3 | [P in keyof T]: ObjPathProxy; 4 | }; 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | .nyc_output 4 | .DS_Store 5 | *.log 6 | .vscode 7 | .idea 8 | dist 9 | compiled 10 | .awcache -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | #root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | max_line_length = 100 10 | indent_size = 2 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | branches: 3 | only: 4 | - master 5 | - /^greenkeeper/.*$/ 6 | cache: 7 | yarn: true 8 | directories: 9 | - node_modules 10 | notifications: 11 | email: false 12 | node_js: 13 | - node 14 | script: 15 | - npm run test:prod && npm run build 16 | after_success: 17 | - npm run report-coverage 18 | - npm run deploy-docs 19 | - npm run semantic-release 20 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "target": "es5", 5 | "module":"es2015", 6 | "lib": ["es2015", "es2016", "es2017", "dom"], 7 | "strict": true, 8 | "sourceMap": true, 9 | "declaration": true, 10 | "allowSyntheticDefaultImports": true, 11 | "experimentalDecorators": true, 12 | "emitDecoratorMetadata": true, 13 | "declarationDir": "dist/types", 14 | "outDir": "compiled", 15 | "typeRoots": [ 16 | "node_modules/@types" 17 | ] 18 | }, 19 | "include": [ 20 | "src" 21 | ] 22 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | We're really glad you're reading this, because we need volunteer developers to help this project come to fruition. 👏 2 | 3 | ## Instructions 4 | 5 | These steps will guide you through contributing to this project: 6 | 7 | - Fork the repo 8 | - Clone it and install dependencies 9 | 10 | git clone https://github.com/YOUR-USERNAME/typescript-library-starter 11 | npm install 12 | 13 | Keep in mind that after running `npm install` the git repo is reset. So a good way to cope with this is to have a copy of the folder to push the changes, and the other to try them. 14 | 15 | Make and commit your changes. Make sure the commands npm run build and npm run test:prod are working. 16 | 17 | Finally send a [GitHub Pull Request](https://github.com/alexjoverm/typescript-library-starter/compare?expand=1) with a clear list of what you've done (read more [about pull requests](https://help.github.com/articles/about-pull-requests/)). Make sure all of your commits are atomic (one feature per commit). 18 | -------------------------------------------------------------------------------- /tools/gh-pages-publish.ts: -------------------------------------------------------------------------------- 1 | const { cd, exec, echo, touch } = require("shelljs") 2 | const { readFileSync } = require("fs") 3 | const url = require("url") 4 | 5 | let repoUrl 6 | let pkg = JSON.parse(readFileSync("package.json") as any) 7 | if (typeof pkg.repository === "object") { 8 | if (!pkg.repository.hasOwnProperty("url")) { 9 | throw new Error("URL does not exist in repository section") 10 | } 11 | repoUrl = pkg.repository.url 12 | } else { 13 | repoUrl = pkg.repository 14 | } 15 | 16 | let parsedUrl = url.parse(repoUrl) 17 | let repository = (parsedUrl.host || "") + (parsedUrl.path || "") 18 | let ghToken = process.env.GH_TOKEN 19 | 20 | echo("Deploying docs!!!") 21 | cd("dist/docs") 22 | touch(".nojekyll") 23 | exec("git init") 24 | exec("git add .") 25 | exec('git config user.name ""') 26 | exec('git config user.email ""') 27 | exec('git commit -m "docs(docs): update gh-pages"') 28 | exec( 29 | `git push --force --quiet "https://${ghToken}@${repository}" master:gh-pages` 30 | ) 31 | echo("Docs deployed!!") 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 <> 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /rollup.config.ts: -------------------------------------------------------------------------------- 1 | import resolve from 'rollup-plugin-node-resolve' 2 | import commonjs from 'rollup-plugin-commonjs' 3 | import sourceMaps from 'rollup-plugin-sourcemaps' 4 | 5 | const pkg = require('./package.json') 6 | 7 | const libraryName = 'ts-object-path' 8 | 9 | export default { 10 | input: `compiled/${libraryName}.js`, 11 | output: [ 12 | { file: pkg.main, name: libraryName, format: 'umd' }, 13 | { file: pkg.module, format: 'es' }, 14 | ], 15 | sourcemap: true, 16 | // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash') 17 | external: [], 18 | watch: { 19 | include: 'compiled/**', 20 | }, 21 | plugins: [ 22 | // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs) 23 | commonjs(), 24 | // Allow node_modules resolution, so you can use 'external' to control 25 | // which external modules to include in the bundle 26 | // https://github.com/rollup/rollup-plugin-node-resolve#usage 27 | resolve(), 28 | 29 | // Resolve source maps to the original source 30 | sourceMaps(), 31 | ], 32 | } 33 | -------------------------------------------------------------------------------- /tools/semantic-release-prepare.ts: -------------------------------------------------------------------------------- 1 | const path = require("path") 2 | const { fork } = require("child_process") 3 | const colors = require("colors") 4 | 5 | const { readFileSync, writeFileSync } = require("fs") 6 | const pkg = JSON.parse( 7 | readFileSync(path.resolve(__dirname, "..", "package.json")) 8 | ) 9 | 10 | pkg.scripts.prepush = "npm run test:prod && npm run build" 11 | pkg.scripts.commitmsg = "validate-commit-msg" 12 | 13 | writeFileSync( 14 | path.resolve(__dirname, "..", "package.json"), 15 | JSON.stringify(pkg, null, 2) 16 | ) 17 | 18 | // Call husky to set up the hooks 19 | fork(path.resolve(__dirname, "..", "node_modules", "husky", "bin", "install")) 20 | 21 | console.log() 22 | console.log(colors.green("Done!!")) 23 | console.log() 24 | 25 | if (pkg.repository.url.trim()) { 26 | console.log(colors.cyan("Now run:")) 27 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 28 | console.log(colors.cyan(" semantic-release setup")) 29 | console.log() 30 | console.log( 31 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 32 | ) 33 | console.log() 34 | console.log( 35 | colors.gray( 36 | 'Note: Make sure "repository.url" in your package.json is correct before' 37 | ) 38 | ) 39 | } else { 40 | console.log( 41 | colors.red( 42 | 'First you need to set the "repository.url" property in package.json' 43 | ) 44 | ) 45 | console.log(colors.cyan("Then run:")) 46 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 47 | console.log(colors.cyan(" semantic-release setup")) 48 | console.log() 49 | console.log( 50 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 51 | ) 52 | } 53 | 54 | console.log() 55 | -------------------------------------------------------------------------------- /src/ts-object-path.ts: -------------------------------------------------------------------------------- 1 | import { ObjPathProxy } from './obj-path-proxy'; 2 | export * from './obj-path-proxy'; 3 | 4 | export type ObjProxyArg = ObjPathProxy | ((p: ObjPathProxy)=> ObjPathProxy); 5 | 6 | const pathSymbol = Symbol('Object path'); 7 | 8 | export function createProxy(path: PropertyKey[] = []): ObjPathProxy { 9 | const proxy = new Proxy({[pathSymbol]: path}, { 10 | get (target, key) { 11 | if (key === pathSymbol) { 12 | return target[pathSymbol]; 13 | } 14 | if (typeof key === 'string') { 15 | const intKey = parseInt(key, 10); 16 | if (key === intKey.toString()) { 17 | key = intKey; 18 | } 19 | } 20 | return createProxy([...(path || []), key]); 21 | } 22 | }); 23 | return proxy as any as ObjPathProxy; 24 | } 25 | 26 | export function getPath(proxy: ObjProxyArg): PropertyKey[] { 27 | if (typeof proxy === 'function') { 28 | proxy = proxy(createProxy()) 29 | } 30 | return (proxy as any)[pathSymbol]; 31 | } 32 | 33 | export function isProxy(value: any): value is ObjPathProxy { 34 | return value && typeof value === 'object' && !!getPath(value as ObjPathProxy); 35 | } 36 | 37 | export function get(object: TRoot, proxy: ObjProxyArg, defaultValue: T|null|undefined = undefined) { 38 | return getPath(proxy).reduce((o, key) => o && valueOrElseDefault(o[key], defaultValue), object as any) as T; 39 | } 40 | 41 | export function set(object: TRoot, proxy: ObjProxyArg, value: T): void { 42 | getPath(proxy).reduce((o: any, key, index, keys) => { 43 | if (index < keys.length - 1) { 44 | o[key] = o[key] || (typeof keys[index + 1] === 'number' ? [] : {}); 45 | return o[key]; 46 | } 47 | o[key] = value; 48 | }, object); 49 | } 50 | 51 | export function valueOrElseDefault(value: T, defaultValue: T):T { 52 | return value !== null && value !== undefined ? value : defaultValue 53 | } 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ts-object-path 2 | Generate strongly-typed deep property path in typescript. Access deep property by a path. 3 | 4 | [![npm version](https://badge.fury.io/js/ts-object-path.svg)](https://badge.fury.io/js/ts-object-path) 5 | 6 | ## Install 7 | ``` 8 | npm install ts-object-path --save 9 | ``` 10 | 11 | ## Usage 12 | 13 | ### Get property path 14 | ```typescript 15 | import { createProxy, getPath } from 'ts-object-path' 16 | 17 | interface IExample { 18 | one: number; 19 | two: string; 20 | nested: IExample; 21 | collection: IExample[]; 22 | } 23 | 24 | const p = createProxy(); 25 | 26 | getPath(p.one); // returns ['one'] 27 | getPath(p.nested.one); // returns ['nested', 'one'] 28 | getPath(p.collection[5].nested.two); // returns ['collection', 5, 'nested', 'two'] 29 | getPath(p.three); // compilation error (no such property) 30 | 31 | ``` 32 | 33 | ### Get deep property value 34 | ```typescript 35 | import { get } from 'ts-object-path' 36 | 37 | interface IExample { 38 | one?: number; 39 | two?: string; 40 | nested?: IExample; 41 | collection?: IExample[]; 42 | } 43 | 44 | const o: IExample = { 45 | one: 777; 46 | collection: [ 47 | null, 48 | { two: 'Hello' } 49 | ] 50 | }; 51 | 52 | get(o, p=> p.one); // returns 777 53 | get(o, p=> p.nested.one); // returns undefined 54 | get(o, p=> p.collection[1].two); // returns 'Hello' 55 | get(o, p=> p.collection[0].two, 'default'); // returns 'default' 56 | get(o, p=> p.collection[0].one, 'default'); // compilation error (property and default value types don't match) 57 | get(o, p=> p.three); // compilation error (no such property) 58 | const val: number = get(o, p=> p.collection[1].two); // compilation error (string is not assignable to number) 59 | 60 | ``` 61 | 62 | ### Set deep property value 63 | ```typescript 64 | import { set } from 'ts-object-path' 65 | 66 | interface IExample { 67 | one?: number; 68 | two?: string; 69 | nested?: IExample; 70 | collection?: IExample[]; 71 | } 72 | 73 | const o: IExample = { 74 | one: 1; 75 | }; 76 | 77 | set(o, p=> p.one, 777); // o === { one: 777 } 78 | set(o, p=> p.nested.one, 3); // o === { one: 777, nested: { one: 3 } } 79 | set(o, p=> p.collection[1].two, 'hello'); // o === { one: 777, nested: { one: 3 }, collection: [undefined, { two: 'hello'}] } 80 | 81 | ``` 82 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ts-object-path", 3 | "version": "0.1.2", 4 | "description": "", 5 | "keywords": [], 6 | "main": "dist/ts-object-path.umd.js", 7 | "module": "dist/ts-object-path.es5.js", 8 | "typings": "dist/types/ts-object-path.d.ts", 9 | "files": [ 10 | "dist" 11 | ], 12 | "author": "Taras Tymchii", 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/Taras-Tymchiy/ts-object-path.git" 16 | }, 17 | "license": "MIT", 18 | "engines": { 19 | "node": ">=6.0.0" 20 | }, 21 | "scripts": { 22 | "lint": "tslint -t codeFrame 'src/**/*.ts' 'test/**/*.ts'", 23 | "prebuild": "rimraf dist", 24 | "build": "tsc && rollup -c rollup.config.ts && rimraf compiled", 25 | "start": "tsc -w & rollup -c rollup.config.ts -w", 26 | "test": "jest", 27 | "test:watch": "jest --watch", 28 | "test:prod": "npm run lint && npm run test -- --coverage --no-cache", 29 | "deploy-docs": "ts-node tools/gh-pages-publish", 30 | "report-coverage": "cat ./coverage/lcov.info | coveralls", 31 | "commit": "git-cz", 32 | "semantic-release": "semantic-release pre && npm publish && semantic-release post", 33 | "semantic-release-prepare": "ts-node tools/semantic-release-prepare", 34 | "precommit": "lint-staged" 35 | }, 36 | "lint-staged": { 37 | "{src,test}/**/*.ts": [ 38 | "prettier --write --no-semi --single-quote", 39 | "git add" 40 | ] 41 | }, 42 | "config": { 43 | "commitizen": { 44 | "path": "node_modules/cz-conventional-changelog" 45 | }, 46 | "validate-commit-msg": { 47 | "types": "conventional-commit-types", 48 | "helpMessage": "Use \"npm run commit\" instead, we use conventional-changelog format :) (https://github.com/commitizen/cz-cli)" 49 | } 50 | }, 51 | "jest": { 52 | "transform": { 53 | ".(ts|tsx)": "/node_modules/ts-jest/preprocessor.js" 54 | }, 55 | "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", 56 | "moduleFileExtensions": [ 57 | "ts", 58 | "tsx", 59 | "js" 60 | ], 61 | "coveragePathIgnorePatterns": [ 62 | "/node_modules/", 63 | "/test/" 64 | ], 65 | "coverageThreshold": { 66 | "global": { 67 | "branches": 80, 68 | "functions": 95, 69 | "lines": 95, 70 | "statements": 95 71 | } 72 | }, 73 | "collectCoverage": true, 74 | "mapCoverage": true 75 | }, 76 | "devDependencies": { 77 | "@types/jest": "^21.1.0", 78 | "@types/node": "^8.0.0", 79 | "colors": "^1.1.2", 80 | "commitizen": "^2.9.6", 81 | "coveralls": "^3.0.0", 82 | "cross-env": "^5.0.1", 83 | "cz-conventional-changelog": "^2.0.0", 84 | "husky": "^0.14.0", 85 | "jest": "^21.0.0", 86 | "lint-staged": "^5.0.0", 87 | "prettier": "^1.4.4", 88 | "prompt": "^1.0.0", 89 | "replace-in-file": "^3.0.0-beta.2", 90 | "rimraf": "^2.6.1", 91 | "rollup": "^0.51.0", 92 | "rollup-plugin-commonjs": "^8.0.2", 93 | "rollup-plugin-node-resolve": "^3.0.0", 94 | "rollup-plugin-sourcemaps": "^0.4.2", 95 | "semantic-release": "^8.0.0", 96 | "ts-jest": "^21.0.0", 97 | "ts-node": "^3.0.6", 98 | "tslint": "^5.4.3", 99 | "tslint-config-prettier": "^1.1.0", 100 | "tslint-config-standard": "^7.0.0", 101 | "typescript": "^2.7", 102 | "validate-commit-msg": "^2.12.2" 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at alexjovermorales@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /test/ts-object-path.test.ts: -------------------------------------------------------------------------------- 1 | import { createProxy, isProxy, getPath, get, set } from "../src/ts-object-path" 2 | import {} from 'jest'; 3 | 4 | interface ITest { 5 | one: number; 6 | two?: string; 7 | three?: INestedTest; 8 | four?: INestedTest[]; 9 | } 10 | 11 | interface INestedTest { 12 | firrst: number; 13 | second?: string; 14 | } 15 | 16 | describe("createProxy test", () => { 17 | it("Creates proxy", () => { 18 | const p = createProxy(); 19 | expect(p).toBeTruthy() 20 | }) 21 | }) 22 | 23 | describe("getPath test", () => { 24 | it("Creates proxy with empty path", () => { 25 | const p = createProxy(); 26 | expect(getPath(p)).toEqual([]); 27 | }) 28 | it("Gets path from proxy", () => { 29 | const p = createProxy(); 30 | expect(getPath(p.one)).toEqual(['one']); 31 | expect(getPath(p.three.second)).toEqual(['three', 'second']); 32 | expect(getPath(p.four[4].second)).toEqual(['four', 4, 'second']); 33 | }) 34 | it("Get undefined", () => { 35 | expect(getPath({})).toBeUndefined(); 36 | }) 37 | }) 38 | 39 | 40 | describe("isProxy test", () => { 41 | it("Returns true for proxies", () => { 42 | const p = createProxy(); 43 | expect(isProxy(p)).toBeTruthy(); 44 | expect(isProxy(p.three.firrst)).toBeTruthy(); 45 | }) 46 | it("Returns false for not proxies", () => { 47 | const p: any = {}; 48 | expect(isProxy(p)).toBeFalsy(); 49 | expect(isProxy(p.three)).toBeFalsy(); 50 | expect(isProxy(undefined)).toBeFalsy(); 51 | expect(isProxy(false)).toBeFalsy(); 52 | expect(isProxy(7)).toBeFalsy(); 53 | expect(isProxy('test')).toBeFalsy(); 54 | }) 55 | }) 56 | 57 | 58 | describe("getValue test", () => { 59 | it("Works with proxy", () => { 60 | const p = createProxy(); 61 | const o: ITest = { one: 4 }; 62 | const v = get(o, p.one); 63 | expect(v).toEqual(o.one); 64 | }) 65 | it("Works with callback", () => { 66 | const v = get({ one: 4 }, p=> p.one); 67 | expect(v).toEqual(4); 68 | }) 69 | it("Works with deep props", () => { 70 | let o: ITest; 71 | expect(get(o, p=> p.three.firrst)).toBeUndefined(); 72 | 73 | o = { one: 5, three: { firrst: 4 } }; 74 | expect(get(o, p=> p.three.firrst)).toEqual(o.three.firrst); 75 | }) 76 | it("Works with arrays", () => { 77 | const o: ITest = { one: 5, four: [null, { firrst: 4 }] }; 78 | expect(get(o, p=> p.four[0].firrst)).toBeUndefined(); 79 | expect(get(o, p=> p.four[1].firrst)).toEqual(4); 80 | }) 81 | it("Works with symbols", () => { 82 | const symb = Symbol('test'); 83 | const o = { regularProp: { [symb]: 333 } }; 84 | const v = get(o, p=> p.regularProp[symb]); 85 | expect(v).toEqual(333); 86 | }) 87 | it("returns default value", () => { 88 | const o: ITest = { one: 4 }; 89 | const v = get(o, p=> p.three.second, 'default' as string); 90 | expect(v).toEqual('default'); 91 | }) 92 | 93 | }) 94 | 95 | describe("setValue test", () => { 96 | it("Works with proxy", () => { 97 | const p = createProxy(); 98 | const o: ITest = { one: 4 }; 99 | set(o, p.one, 333); 100 | expect(o.one).toEqual(333); 101 | }) 102 | it("Works with callback", () => { 103 | const o: ITest = { one: 4 }; 104 | set(o, p=> p.one, 333); 105 | expect(o.one).toEqual(333); 106 | }) 107 | it("Works with deep props", () => { 108 | let o: ITest = { one: 5, three: { firrst: 4 } }; 109 | set(o, p=> p.three.firrst, 777); 110 | expect(o.three.firrst).toEqual(777); 111 | }) 112 | it("Works with arrays", () => { 113 | const o: ITest = { one: 5, four: [null, { firrst: 4 }] }; 114 | set(o, p=> p.four[1].firrst, 666); 115 | expect(o.four[1].firrst).toEqual(666); 116 | }) 117 | 118 | it("Works with symbols", () => { 119 | const symb = Symbol('test'); 120 | const o = { regularProp: { [symb]: 333 } }; 121 | set(o, p=> p.regularProp[symb], 555); 122 | expect(o.regularProp[symb]).toEqual(555); 123 | }) 124 | 125 | it("Creates nested objects", () => { 126 | const o: ITest = { one: 5 }; 127 | set(o, p=> p.three.firrst, 777); 128 | expect(o.three.firrst).toEqual(777); 129 | }) 130 | it("Creates nested arrays", () => { 131 | const o: ITest = { one: 5 }; 132 | set(o, p=> p.four[1].firrst, 666); 133 | expect(o.four[1].firrst).toEqual(666); 134 | expect(o.four).toHaveLength(2); 135 | }) 136 | }) 137 | 138 | describe("regression tests", () => { 139 | it("issue #3 get() returns undefined for value zero", () => { 140 | const p = createProxy(); 141 | const o: ITest = { one: 0 }; 142 | const v = get(o, p.one); 143 | expect(v).toEqual(o.one); 144 | }) 145 | }) 146 | 147 | --------------------------------------------------------------------------------