From 35d18070ace6067f32fcb150c5af246dcf925ce2 Mon Sep 17 00:00:00 2001 From: Antoine Aflalo Date: Mon, 13 Sep 2021 17:44:01 -0400 Subject: [PATCH] feat(GetIndexValue): Get index of a value in an array Fixes #191 --- src/JsonDB.ts | 19 ++++++++++++++++--- test/04-array-utils.test.ts | 11 +++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/JsonDB.ts b/src/JsonDB.ts index 527b5552..1c7592a6 100644 --- a/src/JsonDB.ts +++ b/src/JsonDB.ts @@ -5,7 +5,7 @@ import * as mkdirp from "mkdirp" import {DatabaseError, DataError} from "./lib/Errors" import {DBParentData} from "./lib/DBParentData" import {ArrayInfo} from "./lib/ArrayInfo" -import { Config, JsonDBConfig } from "./lib/JsonDBConfig" +import {Config, JsonDBConfig} from "./lib/JsonDBConfig" type DataPath = Array @@ -186,13 +186,26 @@ export class JsonDB { * @param propertyName name of the property to look for searchValue */ public getIndex(dataPath: string, searchValue: (string | number), propertyName:string = 'id'): number { + const data = this.getArrayData(dataPath); + return data.map(function (element:any) {return element[propertyName];}).indexOf(searchValue); + } + + /** + * Return the index of the value inside the array. Returns -1, if no match is found. + * @param dataPath base dataPath from where to start searching + * @param searchValue value to look for in the dataPath + */ + public getIndexValue(dataPath: string, searchValue: (string | number)) : number { + return this.getArrayData(dataPath).indexOf(searchValue); + } + + private getArrayData(dataPath: string) { const result = this.getData(dataPath); if (!Array.isArray(result)) { throw new DataError(`DataPath: ${dataPath} is not an array.`, 11) } const path = this.processDataPath(dataPath); - const data = this.retrieveData(path, false); - return data.map(function (element:any) {return element[propertyName];}).indexOf(searchValue); + return this.retrieveData(path, false); } /** diff --git a/test/04-array-utils.test.ts b/test/04-array-utils.test.ts index 9d81668e..e3548c67 100644 --- a/test/04-array-utils.test.ts +++ b/test/04-array-utils.test.ts @@ -60,6 +60,17 @@ describe('Array Utils', () => { expect(db.getIndex("/recipes", 12335373873, "test")).toBe(2); }) + test('should get the index of an array with string', () => { + + db.push("/indexValue[]", "abc", true); + db.push("/indexValue[]", "def", true); + db.push("/indexValue[]", "gh", true); + + expect(db.getIndexValue("/indexValue", "abc")).toBe(0); + expect(db.getIndexValue("/indexValue", "def")).toBe(1); + expect(db.getIndexValue("/indexValue", "gh")).toBe(2); + }) + }) describe('Cleanup', () => { test('should remove the test files', () => {