Duplicate sortObjectPropertiesRecursively

This commit is contained in:
nojaf
2024-09-02 14:31:07 +02:00
parent e3caeae15d
commit 12abcccc81
2 changed files with 22 additions and 4 deletions

View File

@@ -94,17 +94,18 @@ export class NotebookSerializer implements vscode.NotebookSerializer {
}
private serializeNotebookToJSON(notebookContent: Partial<nbformat.INotebookContent>, indentAmount: string): Promise<string> {
// ipynb always ends with a trailing new line (we add this so that SCMs do not show unnecessary changes, resulting from a missing trailing new line).
const sorted = sortObjectPropertiesRecursively(notebookContent);
const isInNodeJSContext = typeof process !== 'undefined' && process.release && process.release.name === 'node';
const experimentalSave = vscode.workspace.getConfiguration('ipynb').get('experimental.serialization', false);
if (isInNodeJSContext && experimentalSave) {
return this.serializeViaWorker({
notebookContent: sorted,
notebookContent,
indentAmount
});
} else {
// ipynb always ends with a trailing new line (we add this so that SCMs do not show unnecessary changes, resulting from a missing trailing new line).
const sorted = sortObjectPropertiesRecursively(notebookContent);
return Promise.resolve(JSON.stringify(sorted, undefined, indentAmount));
}
}

View File

@@ -6,8 +6,25 @@
import { notebookSerializationWorkerData } from './common';
import { workerData, parentPort } from 'node:worker_threads';
function sortObjectPropertiesRecursively(obj: any): any {
if (Array.isArray(obj)) {
return obj.map(sortObjectPropertiesRecursively);
}
if (obj !== undefined && obj !== null && typeof obj === 'object' && Object.keys(obj).length > 0) {
return (
Object.keys(obj)
.sort()
.reduce<Record<string, any>>((sortedObj, prop) => {
sortedObj[prop] = sortObjectPropertiesRecursively(obj[prop]);
return sortedObj;
}, {}) as any
);
}
return obj;
}
if (parentPort) {
const { notebookContent, indentAmount } = <notebookSerializationWorkerData>workerData;
const json = JSON.stringify(notebookContent, undefined, indentAmount) + '\n';
const json = JSON.stringify(sortObjectPropertiesRecursively(notebookContent), undefined, indentAmount) + '\n';
parentPort.postMessage(json);
}