Skip to content

Commit

Permalink
feat(GetIndexValue): Get index of a value in an array
Browse files Browse the repository at this point in the history
Fixes #191
  • Loading branch information
Belphemur committed Sep 13, 2021
1 parent 9753288 commit 35d1807
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
19 changes: 16 additions & 3 deletions src/JsonDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>

Expand Down Expand Up @@ -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);
}

/**
Expand Down
11 changes: 11 additions & 0 deletions test/04-array-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit 35d1807

Please sign in to comment.