[Functional Programming] Write a strBuilder function to take unary params

Requirements:

function strBuilder(str) {
    return strBuilder; // TODO
}

var hello = strBuilder("Hello, ");
var kyle = hello("Kyle");
var susan = hello("Susan");
var question = kyle("?")();
var greeting = susan("!")();

console.log(strBuilder("Hello, ")("")("Kyle")(".")("")() === "Hello, Kyle.");
console.log(hello() === "Hello, ");
console.log(kyle() === "Hello, Kyle");
console.log(susan() === "Hello, Susan");
console.log(question === "Hello, Kyle?");
console.log(greeting === "Hello, Susan!");

.

.

.

.

Answer:

function strBuilder(str1) {
  return function appendStr(str2) {
    if (str2 == null) {
      return str1
    }
    return strBuilder(str1 + str2)
  }
}

 

posted @ 2022-08-03 19:56  Zhentiw  阅读(22)  评论(0编辑  收藏  举报