Skip to content

Commit

Permalink
Refactor: Use WeakMap for internal cache (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
kenrick95 authored Sep 6, 2024
1 parent 0efa286 commit ed5a2ad
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 14 deletions.
2 changes: 0 additions & 2 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable import/export */

export interface Options {
/**
Recursively sort keys, including keys of objects inside arrays.
Expand Down
21 changes: 9 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,16 @@ export default function sortKeys(object, options = {}) {
}

const {deep, compare} = options;
const seenInput = [];
const seenOutput = [];
const cache = new WeakMap();

const deepSortArray = array => {
const seenIndex = seenInput.indexOf(array);
if (seenIndex !== -1) {
return seenOutput[seenIndex];
const resultFromCache = cache.get(array);
if (resultFromCache !== undefined) {
return resultFromCache;
}

const result = [];
seenInput.push(array);
seenOutput.push(result);
cache.set(array, result);

result.push(...array.map(item => {
if (Array.isArray(item)) {
Expand All @@ -35,16 +33,15 @@ export default function sortKeys(object, options = {}) {
};

const _sortKeys = object => {
const seenIndex = seenInput.indexOf(object);
if (seenIndex !== -1) {
return seenOutput[seenIndex];
const resultFromCache = cache.get(object);
if (resultFromCache !== undefined) {
return resultFromCache;
}

const result = {};
const keys = Object.keys(object).sort(compare);

seenInput.push(object);
seenOutput.push(result);
cache.set(object, result);

for (const key of keys) {
const value = object[key];
Expand Down

0 comments on commit ed5a2ad

Please sign in to comment.