@tamtamchik/json-deep-sort 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="uk.co.ben_gibson.git.link.SettingsState">
4
+ <option name="host" value="72037fcc-cb9c-4c22-960a-ffe73fd5e229" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,13 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="WEB_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
6
+ <excludeFolder url="file://$MODULE_DIR$/.tmp" />
7
+ <excludeFolder url="file://$MODULE_DIR$/temp" />
8
+ <excludeFolder url="file://$MODULE_DIR$/tmp" />
9
+ </content>
10
+ <orderEntry type="inheritedJdk" />
11
+ <orderEntry type="sourceFolder" forTests="false" />
12
+ </component>
13
+ </module>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/json-deep-sort.iml" filepath="$PROJECT_DIR$/.idea/json-deep-sort.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
package/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Yuri Tkachenko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # JSON Deep Sort
2
+
3
+ ![npm](https://img.shields.io/npm/v/json-deep-sort)
4
+ ![license](https://img.shields.io/npm/l/json-deep-sort)
5
+
6
+ JSON Deep Sort is a comprehensive package that provides flexible sorting of JSON objects by keys. This
7
+ TypeScript-written package can handle deeply nested objects and arrays, and offers both synchronous and asynchronous
8
+ operations.
9
+
10
+ ## Features
11
+
12
+ - Efficiently sorts keys in JSON objects and arrays.
13
+ - Handles deeply nested JSON objects and arrays.
14
+ - Provides both synchronous and asynchronous sorting operations.
15
+ - Written in TypeScript for robust typing and error checking.
16
+
17
+ ## Installation
18
+
19
+ Using npm:
20
+
21
+ ```shell
22
+ npm install json-deep-sort
23
+ ```
24
+
25
+ Using yarn:
26
+
27
+ ```shell
28
+ yarn add json-deep-sort
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ Import JSON Deep Sort in your TypeScript file:
34
+
35
+ ```typescript
36
+ import { sort } from '@tamtamchik/json-deep-sort';
37
+ ```
38
+
39
+ Here is an example of sorting a JSON object:
40
+
41
+ ```typescript
42
+ let data = {
43
+ b: 'b',
44
+ a: 'a',
45
+ c: {
46
+ d: 'd',
47
+ c: 'c',
48
+ a: 'a',
49
+ b: 'b'
50
+ }
51
+ };
52
+ let sortedData = sort(data, true);
53
+ console.log(sortedData); // { a: 'a', b: 'b', c: { a: 'a', b: 'b', c: 'c', d: 'd' } }
54
+ ```
55
+
56
+ ## Contributing
57
+
58
+ Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
59
+
60
+ ## License
61
+
62
+ JSON Deep Sort is [MIT licensed](./LICENSE).
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Function to sort JSON data.
3
+ * @param {any} data - The data to be sorted.
4
+ * @param {boolean} [asc=true] - Whether to sort in ascending order.
5
+ * @returns {any} The sorted data.
6
+ * @throws {Error} If the data is not an object or array.
7
+ */
8
+ export declare function sort(data: any, asc?: boolean): any;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sort = void 0;
4
+ /**
5
+ * Enumeration of data types.
6
+ * @enum {string}
7
+ */
8
+ var DataType;
9
+ (function (DataType) {
10
+ DataType["OBJECT"] = "OBJECT";
11
+ DataType["ARRAY"] = "ARRAY";
12
+ DataType["STRING"] = "STRING";
13
+ DataType["OTHER"] = "OTHER";
14
+ })(DataType || (DataType = {}));
15
+ /**
16
+ * Function to determine the data type of the provided data.
17
+ * @param {any} data - The data to be checked.
18
+ * @returns {DataType} The DataType value corresponding to the data's type.
19
+ */
20
+ function getType(data) {
21
+ const objectConstructor = {}.constructor;
22
+ const arrayConstructor = [].constructor;
23
+ const stringConstructor = ''.constructor;
24
+ if (data && data.constructor === objectConstructor) {
25
+ return DataType.OBJECT;
26
+ }
27
+ else if (data && data.constructor === arrayConstructor) {
28
+ return DataType.ARRAY;
29
+ }
30
+ else if (data && data.constructor === stringConstructor) {
31
+ return DataType.STRING;
32
+ }
33
+ else {
34
+ return DataType.OTHER;
35
+ }
36
+ }
37
+ /**
38
+ * Function to sort JSON data.
39
+ * @param {any} data - The data to be sorted.
40
+ * @param {boolean} [asc=true] - Whether to sort in ascending order.
41
+ * @returns {any} The sorted data.
42
+ * @throws {Error} If the data is not an object or array.
43
+ */
44
+ function sort(data, asc = true) {
45
+ switch (getType(data)) {
46
+ case DataType.ARRAY:
47
+ return data.map((d) => [DataType.OBJECT, DataType.ARRAY].includes(getType(d)) ? sort(d, asc) : d);
48
+ case DataType.OBJECT:
49
+ const keys = Object.keys(data).sort();
50
+ if (!asc)
51
+ keys.reverse();
52
+ return keys.reduce((newData, key) => {
53
+ if ([DataType.OBJECT, DataType.ARRAY].includes(getType(data[key])))
54
+ newData[key] = sort(data[key], asc);
55
+ else
56
+ newData[key] = data[key];
57
+ return newData;
58
+ }, {});
59
+ default:
60
+ throw new Error('Invalid data type: expected an object or array.');
61
+ }
62
+ }
63
+ exports.sort = sort;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Function to sort JSON data.
3
+ * @param {any} data - The data to be sorted.
4
+ * @param {boolean} [asc=true] - Whether to sort in ascending order.
5
+ * @returns {any} The sorted data.
6
+ * @throws {Error} If the data is not an object or array.
7
+ */
8
+ export declare function sort(data: any, asc?: boolean): any;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Enumeration of data types.
3
+ * @enum {string}
4
+ */
5
+ var DataType;
6
+ (function (DataType) {
7
+ DataType["OBJECT"] = "OBJECT";
8
+ DataType["ARRAY"] = "ARRAY";
9
+ DataType["STRING"] = "STRING";
10
+ DataType["OTHER"] = "OTHER";
11
+ })(DataType || (DataType = {}));
12
+ /**
13
+ * Function to determine the data type of the provided data.
14
+ * @param {any} data - The data to be checked.
15
+ * @returns {DataType} The DataType value corresponding to the data's type.
16
+ */
17
+ function getType(data) {
18
+ const objectConstructor = {}.constructor;
19
+ const arrayConstructor = [].constructor;
20
+ const stringConstructor = ''.constructor;
21
+ if (data && data.constructor === objectConstructor) {
22
+ return DataType.OBJECT;
23
+ }
24
+ else if (data && data.constructor === arrayConstructor) {
25
+ return DataType.ARRAY;
26
+ }
27
+ else if (data && data.constructor === stringConstructor) {
28
+ return DataType.STRING;
29
+ }
30
+ else {
31
+ return DataType.OTHER;
32
+ }
33
+ }
34
+ /**
35
+ * Function to sort JSON data.
36
+ * @param {any} data - The data to be sorted.
37
+ * @param {boolean} [asc=true] - Whether to sort in ascending order.
38
+ * @returns {any} The sorted data.
39
+ * @throws {Error} If the data is not an object or array.
40
+ */
41
+ export function sort(data, asc = true) {
42
+ switch (getType(data)) {
43
+ case DataType.ARRAY:
44
+ return data.map((d) => [DataType.OBJECT, DataType.ARRAY].includes(getType(d)) ? sort(d, asc) : d);
45
+ case DataType.OBJECT:
46
+ const keys = Object.keys(data).sort();
47
+ if (!asc)
48
+ keys.reverse();
49
+ return keys.reduce((newData, key) => {
50
+ if ([DataType.OBJECT, DataType.ARRAY].includes(getType(data[key])))
51
+ newData[key] = sort(data[key], asc);
52
+ else
53
+ newData[key] = data[key];
54
+ return newData;
55
+ }, {});
56
+ default:
57
+ throw new Error('Invalid data type: expected an object or array.');
58
+ }
59
+ }
package/jest.config.js ADDED
@@ -0,0 +1,6 @@
1
+ module.exports = {
2
+ preset: 'ts-jest',
3
+ testEnvironment: 'node',
4
+ collectCoverage: true,
5
+ coverageReporters: ['text', 'lcov'],
6
+ }
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@tamtamchik/json-deep-sort",
3
+ "version": "0.1.0",
4
+ "description": "A comprehensive utility for sorting JSON objects by keys.",
5
+ "main": "dist/cjs/index.js",
6
+ "module": "dist/esm/index.js",
7
+ "types": "dist/esm/index.d.ts",
8
+ "author": "Yuri Tkachenko <yuri.tam.tkachenko@gmail.com>",
9
+ "license": "MIT",
10
+ "homepage": "https://github.com/tamtamchik/json-deep-sort#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/tamtamchik/json-deep-sort/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+ssh://git@github.com/tamtamchik/json-deep-sort.git"
17
+ },
18
+ "keywords": [
19
+ "json",
20
+ "sort",
21
+ "json-sort",
22
+ "keysort",
23
+ "json-keysort",
24
+ "json-deep-sort",
25
+ "sorting",
26
+ "typescript",
27
+ "async-sort",
28
+ "synchronous-sort",
29
+ "json-manipulation",
30
+ "data-processing",
31
+ "json-utility",
32
+ "json-tools"
33
+ ],
34
+ "exports": {
35
+ ".": {
36
+ "import": "./dist/esm/index.js",
37
+ "require": "./dist/cjs/index.js"
38
+ }
39
+ },
40
+ "directories": {
41
+ "test": "test"
42
+ },
43
+ "devDependencies": {
44
+ "@types/jest": "29.5.1",
45
+ "@types/node": "20.2.5",
46
+ "jest": "29.5.0",
47
+ "ts-jest": "29.1.0",
48
+ "typescript": "5.0.4"
49
+ },
50
+ "scripts": {
51
+ "build:cjs": "tsc -p tsconfig.cjs.json",
52
+ "build:esm": "tsc -p tsconfig.esm.json",
53
+ "build": "npm run build:cjs && npm run build:esm",
54
+ "dev": "tsc --watch",
55
+ "prepare": "npm run build",
56
+ "test": "jest"
57
+ }
58
+ }
package/src/index.ts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Enumeration of data types.
3
+ * @enum {string}
4
+ */
5
+ enum DataType {
6
+ OBJECT = 'OBJECT',
7
+ ARRAY = 'ARRAY',
8
+ STRING = 'STRING',
9
+ OTHER = 'OTHER',
10
+ }
11
+
12
+ /**
13
+ * Function to determine the data type of the provided data.
14
+ * @param {any} data - The data to be checked.
15
+ * @returns {DataType} The DataType value corresponding to the data's type.
16
+ */
17
+ function getType (data: any): DataType {
18
+ const objectConstructor = {}.constructor
19
+ const arrayConstructor = [].constructor
20
+ const stringConstructor = ''.constructor
21
+
22
+ if (data && data.constructor === objectConstructor) {
23
+ return DataType.OBJECT
24
+ } else if (data && data.constructor === arrayConstructor) {
25
+ return DataType.ARRAY
26
+ } else if (data && data.constructor === stringConstructor) {
27
+ return DataType.STRING
28
+ } else {
29
+ return DataType.OTHER
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Function to sort JSON data.
35
+ * @param {any} data - The data to be sorted.
36
+ * @param {boolean} [asc=true] - Whether to sort in ascending order.
37
+ * @returns {any} The sorted data.
38
+ * @throws {Error} If the data is not an object or array.
39
+ */
40
+ export function sort (data: any, asc = true): any {
41
+ switch (getType(data)) {
42
+
43
+ case DataType.ARRAY:
44
+ return data.map((d: any) => [DataType.OBJECT, DataType.ARRAY].includes(getType(d)) ? sort(d, asc) : d)
45
+
46
+ case DataType.OBJECT:
47
+ const keys = Object.keys(data).sort()
48
+
49
+ if (!asc) keys.reverse()
50
+
51
+ return keys.reduce((newData: any, key: string) => {
52
+ if ([DataType.OBJECT, DataType.ARRAY].includes(getType(data[key])))
53
+ newData[key] = sort(data[key], asc)
54
+ else
55
+ newData[key] = data[key]
56
+ return newData
57
+ }, {})
58
+
59
+ default:
60
+ throw new Error('Invalid data type: expected an object or array.')
61
+ }
62
+ }
@@ -0,0 +1,98 @@
1
+ import { sort } from '../src'
2
+
3
+ describe('sort', () => {
4
+ it('should sort an object', () => {
5
+ const input = { b: 'b', a: 'a' }
6
+ const expected = { a: 'a', b: 'b' }
7
+ expect(sort(input)).toEqual(expected)
8
+ })
9
+
10
+ it('should not sort an simple array', () => {
11
+ const input = ['a', 'b']
12
+ const expected = ['a', 'b']
13
+ expect(sort(input)).toEqual(expected)
14
+ })
15
+
16
+ it('should sort an array of objects', () => {
17
+ const input = [
18
+ { b: 'b', a: 'a' },
19
+ { d: 'd', c: 'c' },
20
+ ]
21
+ const expected = [
22
+ { a: 'a', b: 'b' },
23
+ { c: 'c', d: 'd' },
24
+ ]
25
+ expect(sort(input)).toEqual(expected)
26
+ })
27
+
28
+ it('should sort an object with array values', () => {
29
+ const input = {
30
+ b: ['b', 'a'],
31
+ a: ['d', 'c', 'b', 'a'],
32
+ }
33
+ const expected = {
34
+ a: ['d', 'c', 'b', 'a'],
35
+ b: ['b', 'a'],
36
+ }
37
+ expect(sort(input)).toEqual(expected)
38
+ })
39
+
40
+ it('should sort an object with nested objects', () => {
41
+ const input = {
42
+ a: 'a',
43
+ b: {
44
+ b: 'b',
45
+ a: 'a',
46
+ },
47
+ }
48
+ const expected = {
49
+ a: 'a',
50
+ b: {
51
+ a: 'a',
52
+ b: 'b',
53
+ },
54
+ }
55
+ expect(sort(input)).toEqual(expected)
56
+ })
57
+
58
+ it('should not sort an array of simple arrays', () => {
59
+ const input = [
60
+ ['b', 'a'],
61
+ ['d', 'c', 'b', 'a'],
62
+ ]
63
+ const expected = [
64
+ ['b', 'a'],
65
+ ['d', 'c', 'b', 'a'],
66
+ ]
67
+ expect(sort(input)).toEqual(expected)
68
+ })
69
+
70
+ it('should sort an array containing objects', () => {
71
+ const input = [
72
+ { b: 'b', a: 'a' },
73
+ { d: 'd', c: 'c', b: 'b', a: 'a' },
74
+ ]
75
+ const expected = [
76
+ { a: 'a', b: 'b' },
77
+ { a: 'a', b: 'b', c: 'c', d: 'd' },
78
+ ]
79
+ expect(sort(input)).toEqual(expected)
80
+ })
81
+
82
+ it('should sort an object in descending order', () => {
83
+ const input = { b: 'b', a: 'a', c: 'c' }
84
+ const expected = { c: 'c', b: 'b', a: 'a' }
85
+ expect(sort(input, false)).toEqual(expected)
86
+ })
87
+
88
+ it('should throw an error for non-object, non-array input', () => {
89
+ const input = 'string'
90
+ expect(() => sort(input)).toThrow('Invalid data type: expected an object or array.')
91
+
92
+ const inputNumber = 123
93
+ expect(() => sort(inputNumber)).toThrow('Invalid data type: expected an object or array.')
94
+
95
+ const inputNull = null
96
+ expect(() => sort(inputNull)).toThrow('Invalid data type: expected an object or array.')
97
+ })
98
+ })
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "commonjs",
5
+ "outDir": "./dist/cjs",
6
+ }
7
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "es2020",
5
+ "outDir": "./dist/esm",
6
+ }
7
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "compilerOptions": {
3
+ "declaration": true,
4
+ "esModuleInterop": true,
5
+ "strict": true,
6
+ "target": "es6",
7
+ "moduleResolution": "node"
8
+ },
9
+ "include": ["src"],
10
+ "exclude": ["node_modules"]
11
+ }