Search This Blog

2026/09/22

Javascript:TrimLeft & TrimRight

function trimLeft(str) {
  if (typeof str !== 'string') {
    throw new TypeError('Expected a string');
  }
  return str.replace(/^\s+/, '');
}
function trimRight(str) {
  if (typeof str !== 'string') {
    throw new TypeError('Expected a string');
  }
return str.replace(/\s+$/, '');
}

let input = '   Hello, World!   ';
let trimmedLeft = trimLeft(input);
console.log("'" + trimmedLeft + "'"); // Output: 'Hello, World!   '

let trimmedRight = trimRight(input);
console.log("'" + trimmedRight + "'"); // Output: '   Hello, World!'

2026/08/21

Javascript:Leet Code -Find pair of number in array whose sum equal to target




Find a pair of number from array whose sum is equal to target


nums = [2, 7, 11, 15]
target = 9


function targetSumPair(nums, target) {
    arr = []
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if(nums[i]>target && nums[j] > target) continue
            if (nums[i] + nums[j] == target) {
                return [i, j]
            } else {
                console.log(`i=${nums[i]} j=${nums[j]}`)
            }
        }
    }
}

console.log(targetSumPair(nums,target))

Expected Optimized Way:

function targetSumPair(nums, target) {
    let obj = {};

    for (let i = 0; i < nums.length; i++) {
        let complement = target - nums[i];
        if (obj[complement] !== undefined) {
            return [obj[complement], i];
        }

        obj[nums[i]] = i;
    }
}

console.log(targetSumPair([2, 7, 11, 15], 9));{