has #9

Closed
killerbossoriginal wants to merge 1 commit from feature-has into main
3 changed files with 30 additions and 13 deletions

5
.gitignore vendored
View file

@ -1,3 +1,8 @@
node_modules node_modules
package-lock.json package-lock.json
build build
*yarn*
*.tsbuildinfo
tsconfig.tsbuildinfo
*test*

View file

@ -4,7 +4,7 @@ MapDB A Map that stores data locally and loads it at startup. Written in JavaScr
### How does it work? ### How does it work?
Map.db works just like the JavaScript built-in **Map**, with the same methods and functionalities, and in fact it uses itself a Map, but while the built-in Map only stores data in internal memory, this module **stores data locally in a file and loads it back in the Map at startup**. Mit.db works just like the JavaScript built-in **Map**, with the same methods and functionalities, and in fact it uses itself a Map, but while the built-in Map only stores data in internal memory, this module **stores data locally in a file and loads it back in the Map at startup**.
The purpose of this module is to make the JavaScript built-in Map an actual **database**, and there comes the name `mit.db`: a Map that can be used as a database. The purpose of this module is to make the JavaScript built-in Map an actual **database**, and there comes the name `mit.db`: a Map that can be used as a database.
@ -58,5 +58,12 @@ await db.set('what', 'how')
#### get() #### get()
```js ```js
var answ = db.get('what') // answ = how var ansa = db.get('what') // ansa = how
```
#### has()
```js
var ansb = db.has('what') // ansb = true
var ansc = db.has('attila') // ansc = false
``` ```

View file

@ -8,10 +8,10 @@ writeDB = fsp.writeFile;
export class MitDB { export class MitDB {
/** /**
* @constructor * @constructor
* @param filename If not set, MapDB will only use internal memory * @param filename If not set, MitDB will only use internal memory
* @example 'file.db' * @example 'file.db'
* @param options Options to pass to the constructor * @param options Options to pass to the constructor
* @param options.dirname * @param options.dirname Where to save the file?
* @example 'data' * @example 'data'
*/ */
constructor(fn: string | undefined, options: any) { constructor(fn: string | undefined, options: any) {
@ -58,15 +58,20 @@ export class MitDB {
/** /**
* @param key * @param key
*/ */
get(key: string | number) { get(key: string | number) {
if (map) { file = fs.readFileSync(db);
return map.get(key) data = JSON.parse(file.toString());
} else {
file = fs.readFileSync(db);
data = JSON.parse(file.toString());
return data.find((pair: any) => pair.key == key)?.value || undefined; return data.find((pair: any) => pair.key == key)?.value || undefined;
} }
/**
* @param key
*/
has(key: string | number) {
const file = fs.readFileSync(db);
const data = JSON.parse(file.toString());
return data.find((pair: any) => pair.key == key) ? true : false;
} }
} }