Home > Back-end >  Recursive class function
Recursive class function

Time:07-27

I have code like this with two different classes in two different files. I want to call a class function from another just like in a recursive manner. Can I achieve this in JavaScript?

// lexer/index.js

const Quote = require(./tokenizer/quote.js)
module.exports = class Lexer {

  constructor(args) {
    // some get set method callings
  }
  
  run () {
    return Quote.tokenize(args)
  }
}

// lexer/tokenizer/quote

const Lexer = require('../index')
module.exports = class Quote {
  // no constructor
  // but there could be 

  static tokenize(args) {
    // some calculation for body
    // again call the lexer run
    const quoteLexer = new Lexer(body)
    return quoteLexer.run()
  }
}

// index

const Lexer = require("./lexer")
const l = new Lexer(someContent)
console.log(l.run())

currently, I'm getting the following error while executing this.

> node index.js

/home/kiran/dev/markdown-parser/lib/lexer/tokenizer/quote.js:57
    const quoteLexer = new Lexer(body)
                       ^

TypeError: Lexer is not a constructor
    at Function.tokenize (/home/kiran/dev/markdown-parser/lib/lexer/tokenizer/quote.js:57:24)

Code can be found at https://github.com/kiranparajuli589/markdown-parser/pull/17; To reproduce: just do npm install && npm run convert

CodePudding user response:

Using a code like this solved the problem.

// lexer/index.js
import Quote from "./tokenizer/quote.js"

export default class Lexer{
  run() {
    Quote.tokenize(args)
  }
}
// lexer/tokenizer/quote.js
import Lexer from "../index.js"

export default class Quote {
  tokenize() {
    const l = new Lexer(args)
    console.log(l.run())
  }
}
  • Related