Skip to content

How to compose JS functions with condition check at each step?

I have written my code

function takesst(str) {
  const str1 = [...str];
  const l = str1.length;
  const check = (str1) => (str1.indexOf('(') === 0 && str1.lastIndexOf(')') === l - 1);
  res = check(str1);
  return res;
}

The goal is to check that the first charachter is ( and the last ). Works OK.

node mycode.js
true

Now, the next step would be the high-order function that would include removing first and last character at each step and checking if the condition is met again.

const rec = f => f((...str).slice(1,-1))

String befor and after this step.

'(()())'
'()()'

How to do this?

Answer

You could check for length and if the string starts and ends with wanted characters and the rest fullfills the same objective.

const check = string => !string.length || string.startsWith('(') && string.endsWith(')') && check(string.slice(1, -1));

console.log(check('((()))'));
console.log(check('((())'));