Skip to content

Commit

Permalink
feat(*): initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
rohmanhm committed Nov 23, 2019
0 parents commit 0c0c8f2
Show file tree
Hide file tree
Showing 11 changed files with 6,434 additions and 0 deletions.
29 changes: 29 additions & 0 deletions .github/workflows/pull_requests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: Pull Requests

on:
pull_request:
branches:
- master

jobs:
test:
name: Test on node ${{ matrix.node_version }} and ${{ matrix.os }}
runs-on: ubuntu-latest

strategy:
matrix:
node-version: [11.x]

steps:
- uses: actions/checkout@v1
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: npm install, build and test
run: |
yarn install
yarn build
yarn test
env:
CI: true
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.log
.DS_Store
node_modules
.rts2_cache_cjs
.rts2_cache_esm
.rts2_cache_umd
.rts2_cache_system
dist
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
!/dist
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Rohman Habib M

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:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

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.
75 changes: 75 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# purify-obj

> Purify & clean objects recursively, deleting undefined & null or falsy properties.
## Install

```
$ npm install purify-obj
```

Or

```
$ yarn add purify-obj
```

## Usage

```js
import { PurifyObj } from "purify-obj";
// Or
const { PurifyObj } = require("purify-obj");
// Or you can use the `po` shortcut
import { po } from "purify-obj";

const object = {
className: "only-this-obj-key-will-persist",
disabled: "",
autoComplete: false,
checked: undefined,
spellCheck: null
};
const newObject = po(object);
//=> {className: 'only-this-obj-key-will-persist'}
```

## API

### PurifyObj(source, strict)

#### source

Type: `object`

Source object to purify properties from.

#### strict

Type: `boolean`

Strict will purify all falsy key

## Local Development

Below is a list of commands you will probably find useful.

### `npm start` or `yarn start`

Runs the project in development/watch mode. Your project will be rebuilt upon changes. TSDX has a special logger for you convenience. Error messages are pretty printed and formatted for compatibility VS Code's Problems tab.

Your library will be rebuilt if you make edits.

### `npm run build` or `yarn build`

Bundles the package to the `dist` folder.
The package is optimized and bundled with Rollup into multiple formats (CommonJS, UMD, and ES Module).

### `npm test` or `yarn test`

Runs the test watcher (Jest) in an interactive mode.
By default, runs tests related to files changed since the last commit.

## Related

- [clean-obj](https://github.com/ricardofbarros/clean-obj) - Clean objects recursively, deleting undefined & null or falsy properties.
54 changes: 54 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "purify-obj",
"version": "0.1.0",
"license": "MIT",
"main": "dist/index.js",
"module": "dist/purify-obj.esm.js",
"typings": "dist/index.d.ts",
"repository": "rohmanhm/purify-obj",
"description": "Purify & clean objects recursively, deleting undefined & null or falsy properties.",
"author": {
"name": "Rohman Habib M",
"email": "[email protected]",
"url": "https://rohmanhm.github.com"
},
"keywords": [
"purify",
"clean",
"object",
"key",
"keys",
"value",
"values",
"iterate",
"iterator"
],
"files": [
"dist"
],
"scripts": {
"start": "tsdx watch",
"build": "tsdx build",
"test": "tsdx test",
"lint": "tsdx lint"
},
"peerDependencies": {},
"husky": {
"hooks": {
"pre-commit": "tsdx lint"
}
},
"prettier": {
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "es5"
},
"devDependencies": {
"@types/jest": "^24.0.23",
"husky": "^3.1.0",
"tsdx": "^0.11.0",
"tslib": "^1.10.0",
"typescript": "^3.7.2"
}
}
80 changes: 80 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { isEmpty } from './isEmpty';

// Type of object shape
export type ObjectShape = { [key: string]: any };
// Type of ignored type
export type IgnoredTypes = null | undefined;
// Util to extract type from <T> value
export type MethodKeys<T, U> = {
[P in keyof T]: T[P] extends U ? never : P;
}[keyof T];
// Util to remove ignored key
export type RemoveIgnoredKey<T> = Pick<T, MethodKeys<T, IgnoredTypes>> | null;
// Type object return
export type PurifyObjReturn<ObjectType> = RemoveIgnoredKey<ObjectType>;

const toStr = Object.prototype.toString;

export function PurifyObj<ObjectType extends ObjectShape>(
obj: ObjectType,
strict?: boolean
): PurifyObjReturn<ObjectType> {
strict = strict || false;

let newObj = _purifyObj(obj, strict);

if (newObj === null) {
newObj = {} as any;
}

return newObj;
}

export const po = PurifyObj;

function _purifyObj<ObjectType extends ObjectShape>(
obj: ObjectType,
strict: boolean
): PurifyObjReturn<ObjectType> {
let k: string;
for (k in obj) {
purifyProperty(k, obj[k], obj);
}

// Check if the object is empty
// If it is return null to delete the object
if (!isEmpty(obj)) {
return obj;
} else {
return null;
}

function purifyProperty(key: string, value: any, ref: ObjectShape) {
if (!shouldPurifyProperty(value)) {
delete ref[key];
return;
}

const typeOfValue = typeof value;

// If value is an object (excluding date objects)
if (typeOfValue === 'object' && toStr.call(value) !== '[object Date]') {
// Exception - If array
if (toStr.call(obj[k]) === '[object Array]') {
ref[key] = ref[key].filter(shouldPurifyProperty);
} else {
_purifyObj(ref[key], strict);
}

if (isEmpty(ref[key])) {
delete ref[key];
}
}
}

function shouldPurifyProperty(value: any) {
return !(!value && (strict || (!strict && value == null)));
}
}

export { isEmpty };
19 changes: 19 additions & 0 deletions src/isEmpty.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const hasOwnProp = Object.prototype.hasOwnProperty;

export function isEmpty<ObjectType extends { [key: string]: unknown }>(
obj: ObjectType
) {
// Check if obj has .length property
// and if === 0 - it's empty
if (obj.length) {
return obj.length === 0;
}

// Otherwise, does it have any properties of its own?
for (const key in obj) {
if (hasOwnProp.call(obj, key)) return false;
}

// Fallback
return true;
}
38 changes: 38 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { po } from '../src';

test('remove null and undefined key value', () => {
const expected = {
className: 'only-this-obj-key-will-persist',
disabled: '',
autoComplete: false,
};

const actual = po({
...expected,
disabled: '',
autoComplete: false,
checked: undefined,
spellCheck: null,
});

expect(actual).toEqual(expected);
});

test('strict mode remove falsy key value', () => {
const expected = {
className: 'only-this-obj-key-will-persist',
};

const actual = po(
{
...expected,
disabled: '',
autoComplete: false,
checked: undefined,
spellCheck: null,
},
true
);

expect(actual).toEqual(expected);
});
25 changes: 25 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"include": ["src", "types", "test"],
"compilerOptions": {
"target": "es5",
"module": "esnext",
"lib": ["dom", "esnext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./",
"strict": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"baseUrl": "./",
"esModuleInterop": true
}
}
Loading

0 comments on commit 0c0c8f2

Please sign in to comment.