-3

I'm trying to make a reusable javascript library for example books class and have createbook, checkforbook, modify book methods

I want to use it like so

import Library, {checkForBook, modifyBook} from 'books'


Library.createBook({
 name : 'firstbook',
 year: 2012
})


checkForBook('firstBook')

modifyBook('firstBook',{
  name: 'secondBook'
})

my problem right now is: how to do it without need to use new keywrod , and how to use methods wihout need to make it like Library.checkForBook and still have access to the list of books

mr dev
  • 3
  • 2
  • Add your books script and the current issue that you're facing. Here is a similar question https://stackoverflow.com/questions/38308307/export-import-single-class-method-using-es6-modules – Harshana Mar 23 '19 at 12:19
  • Can you post your `books` module source, please? Are you saying it contains a `class`? – Bergi Mar 23 '19 at 12:30

2 Answers2

0

I think you are looking for

// library.js
export default class Library {
    …
}

// books.js
import Library from './library';

// creates a singleton:
export default const books = new Library();

export function checkForBook(name) {
    return books.checkForBook(name);
}
export function modifyBook(name, value) {
    return books.modifyBook(name, value);
}

// main.js
// imports the singleton, not the `Library` class
import books, {checkForBook, modifyBook} from 'books';

books.createBook({
 name : 'firstbook',
 year: 2012
});

checkForBook('firstBook');

modifyBook('firstBook', {
  name: 'secondBook'
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0
  const books = new Map(); // store the books somehow

  export function createBook({ name, year }) { // make them available as import { createBook } from ...
    const book = { name, year };
    books.set(name, book);
    return book;
  }

  export function checkForBook(name) {
    return books.has(name);
  }

  export function modifyBook(name, update) {
    if(!checkForBook(name))
      throw new Error("Cannot modify, book doesnt exist");
    Object.assign(books.get(name), update);
  }

  export default { // make them available as Library.createBook
    createBook,
    checkForBook,
    modifyBook
  };
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151