iT邦幫忙

0

如何寫JS的callback function

  • 分享至 

  • xImage

大家好,
我想請問一下,要怎麼將這個算式((10^2+6*5)/(9-7))^0.5
寫成callback function呢?

目前我寫到這裡,就卡住了....
/images/emoticon/emoticon46.gif

//((10^2+6*5)/(9-7))^0.5

function twice(x,y){
  return Math.pow(x,y)
}
function times(x,y){
    return x*y
}
function add(x,y){
    return x+y
}
function minus(x,y){
  return x-y
}
function division(x,y){
    return x/y
}

//不知道要怎麼將它改成一個function表示
//雖然這條code,感覺也算是callback function?
twice(division(add(twice(10,2),times(6,5)),minus(9,7)),0.5)

我想試著將它改成這種形式

//code來源 by Summer。桑莫。夏天

getA(function(a) {
  getB(function(b) {
    getC(function(c) {
      console.log(a + b + c); // 6
    });
  });
});

function getA(cb) {
  // 經過冗長運算或從伺服器取得...
  cb(1);
}

function getB(cb) {
  // 經過冗長運算或從伺服器取得...
  cb(2);
}

function getC(cb) {
  // 經過冗長運算或從伺服器取得...
  cb(3);
}
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
HAO
iT邦研究生 3 級 ‧ 2022-05-11 13:23:39
最佳解答

你好,我覺得用 function chaining 的方式來處理是不錯的選擇:

function calc(initialNumber = 0) {
  let num = initialNumber;

  function twice(x) {
    num = Math.pow(num, x);
    return this;
  }
  function times(x) {
    num *= x;
    return this;
  }
  function add(x) {
    num += x;
    return this;
  }
  function minus(x) {
    num -= x;
    return this;
  }
  function division(x) {
    num /= x;
    return this;
  }

  function result() {
    return num;
  }

  return {
    twice,
    times,
    add,
    minus,
    division,
    result
  };
}

這是使用方式:

const first = calc(10).twice(2).result();  // 10^2 = 100
const second = calc(6).times(5).result(); // 6 * 5 = 30
const third = calc(9).minus(7).result(); // 9 - 7 = 2

// ((10^2 + 6 * 5)/(9 - 7))^0.5 = ((100 + 30) / 2)^0.5
const answer = calc(first).add(second).division(third).twice(0.5).result();

console.log(answer); // 8.06225774829855

我要發表回答

立即登入回答