B
B
bzotsss2021-07-07 14:53:20
JavaScript
bzotsss, 2021-07-07 14:53:20

How to use closures to implement the memorization of words?

Hello everyone, I can not implement the task, which consists in the fact that the function needs to "remember" the words that I pass as a parameter. i.e. if I call like this:

const concat = function (str) {
    let word = str;
    return function (newWord) {
        return word + newWord;
    }
}

let memorize = concat('test')
console.log(memorize('test2'))
console.log(memorize('test3'))

That should print "testtest2" the next time you call "testtest2test3" and now it prints testtest2 and then testtest3 . The question is what am I doing wrong? I know that I can shove them into an array, but this solution does not seem very beautiful to me, I would like to solve it using a closure. Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
faleaksey, 2021-07-07
@bzotsss

const concat = function (str) {
  let word = str;
  return function (newWord) {
      return word += newWord;
  }
}

let memorize = concat('test')
console.log(memorize('test2'))
console.log(memorize('test3'))
console.log(memorize('test4'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question