Dart、JavaScript 的一些代码啊啊啊啊啊~

2023-12-11 21:03:01 浏览数 (2)

投石击水,不起浪花,也泛涟漪。

Dart

Call 事件派发与监听

代码语言:javascript复制
class Call {
  Call._internal() {
    // 构建单例,也可直接将 _callBackMap 变为静态成员,代码简洁,但是暴露了 _callBackMap。
  }

  static final Call _instance = Call._internal();

  Map<String, List<Function>> _callBackMap = new Map<String, List<Function>>();

  static bool hasCallBack(String eventKey, Function callback) {
    if (_instance._callBackMap[eventKey] == null) {
      return false;
    }
    return _instance._callBackMap[eventKey].contains(callback);
  }

  static void addCallBack(String eventKey, Function callback) {
    if (_instance._callBackMap[eventKey] == null) {
      _instance._callBackMap[eventKey] = [];
    }
    if (!hasCallBack(eventKey, callback)) {
      _instance._callBackMap[eventKey].add(callback);
    }
  }

  static void removeCallBack(String eventKey, Function callback) {
    if (_instance._callBackMap[eventKey] == null) {
      return;
    }
    _instance._callBackMap[eventKey].removeWhere((callBackFunc) => callBackFunc == callback);
  }

  static void dispatch(String eventKey, {var data}) {
    if (_instance._callBackMap[eventKey] == null) {
      throw Exception('未找到回调事件 $eventKey 的监听');
    }
    _instance._callBackMap[eventKey].forEach((callBackFunc) {
      callBackFunc?.call(data);
    });
  }
}

/* ---------- */

void main() {
  Call.addCallBack('test', (data) {
    print('test1$data');
  });
  var test = (data) {
    print('test2$data');
  };
  Call.addCallBack('test', test);
  Call.dispatch('test', data: '123');
  print('hasCallBack-test${Call.hasCallBack('test', test)}');
  Call.removeCallBack('test', test);
  Call.dispatch('test');
  Call.dispatch('test-not');
}

防抖

代码语言:javascript复制
Function debounce(
  Function func, [
  int delay = 2000,
]) {
  if (func == null) {
    return () {
      print('func is null');
    };
  }
  Timer timer;
  Function target = () {
    if (timer?.isActive ?? false) {
      timer?.cancel();
    }
    timer = Timer(Duration(milliseconds: delay), () {
      func?.call();
    });
  };
  return target;
}

/* ---------- */

void main() async {
  print("Hello, World0!");
  var test = debounce(() {
    print("Hello, World1!");
  }, 5000);
  test();
  await Future.delayed(Duration(milliseconds: 1000));
  test();
  await Future.delayed(Duration(milliseconds: 1000));
  test();
  print("Hello, World2!");
}
// 最后一次才有效,7s多打印一次 Hello, World1!。

节流

代码语言:javascript复制
Function throttle(
  Function func, [
  int delay = 2000,
]) {
  if (func == null) {
    return () {
      print('func is null');
    };
  }
  bool enable = true;
  Function target = () async {
    if (enable == true) {
      enable = false;
      func?.call();
      await Future.delayed(Duration(milliseconds: delay));
      enable = true;
    }
  };
  return target;
}

/* ---------- */

void main() async {
  print("Hello, World0!");
  var test = throttle(() {
    print("Hello, World1!");
  }, 5000);
  test();
  await Future.delayed(Duration(milliseconds: 1000));
  test();
  await Future.delayed(Duration(milliseconds: 1000));
  test();
  print("Hello, World2!");
}
// 第一次才有效,严格意义立即打印一次 Hello, World1!。

http-dao

代码语言:javascript复制
Future fetch() async {
  String getUrl = 'http://localhost:888';
  final Map<String, String> header = {'Content-type': 'application/json', 'authorization': 'Bearer test'};
  var response;
  try {
    response = await http.get(Uri.parse(getUrl), headers: header);
  } catch (e) {
    // ERROR
  }
  Utf8Decoder utf8decoder = Utf8Decoder();
  var result = json.decode(utf8decoder.convert(response.bodyBytes));
  if (response.statusCode == 200 || result['code'] == '0') {
    // Success
  } else {
    // Failed
  }
}

Base64

代码语言:javascript复制
String base64StrEncode(String sourceStr) {
  List<int> bytes = utf8.encode(sourceStr);
  String encodeStr = base64Encode(bytes);
  return encodeStr;
}

String base64StrDecode(String encodedStr) {
  List<int> bytes = base64Decode(encodedStr);
  // String decodeStr = String.fromCharCodes(bytes);
  String decodeStr = utf8.decode(bytes);
  return decodeStr;
}

JavaScript

Call 事件派发与监听

代码语言:javascript复制
export default class Call {
  private static instance: Call;

  private constructor() { } // 不能初始化

  /**
   * 获取 Call 单例
   * @returns 
   */
  static getInstance(): Call {
    if (!this.instance) {
      this.instance = new Call();
    }
    return this.instance;
  }


  private _callBackMap: { [key: string]: Function[] } = {};

  static hasCallBack(eventKey: string, callBack: Function): boolean {
    if (!Call.getInstance()._callBackMap[eventKey]) {
      return false;
    }
    return Call.getInstance()._callBackMap[eventKey]?.includes(callBack) ?? false;
  }

  static addCallBack(eventKey: string, callback: Function): void {
    if (!Call.getInstance()._callBackMap[eventKey]) {
      Call.getInstance()._callBackMap[eventKey] = [];
    }
    if (!Call.hasCallBack(eventKey, callback)) {
      Call.getInstance()._callBackMap[eventKey]?.push(callback);
    }
  }

  static removeCallBack(eventKey: string, callback: Function): void {
    if (!Call.getInstance()._callBackMap[eventKey]) {
      return;
    }
    Call.getInstance()._callBackMap[eventKey] = Call.getInstance()._callBackMap[eventKey]?.filter((callBackFunc) => callBackFunc != callback);
  }

  static dispatch(eventKey: string, ...args: any) {
    if (!Call.getInstance()._callBackMap[eventKey]) {
      throw new Error(`未找到回调事件 ${eventKey} 的监听`);
    }
    Call.getInstance()._callBackMap[eventKey].forEach((callBackFunc) => {
      callBackFunc?.apply(this, args);
    });
  }
}

/* ---------- */

Call.addCallBack('test', function () {
  console.log('test1', arguments);
});
var test = function (data1, data2) {
  console.log('test2', data1, data2);
};
Call.addCallBack('test', test);
Call.dispatch('test', 123, 456);
console.log(
  'hasCallBack-test',
  Call.hasCallBack('test', test),
  Call.hasCallBack('test', () => {})
);
Call.removeCallBack('test', test);
Call.dispatch('test');
Call.dispatch('test-not');

防抖

代码语言:javascript复制
function debounce(fn, delay = 2000) {
  let timer = null;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(this, arguments);
    }, delay);
  };
}

/* ---------- */

async function testFunc() {
  console.time('x');
  console.log('Hello, World0!');
  var test = debounce(function () {
    console.log('Hello, World1!');
    console.timeEnd('x');
  }, 5000);
  test();
  await new Promise((resolve) => {
    setTimeout(() => resolve(), 1000);
  });
  test();
  await new Promise((resolve) => {
    setTimeout(() => resolve(), 1000);
  });
  test();
  console.log('Hello, World2!');
}
testFunc();
// 最后一次才有效,7s多打印一次 Hello, World1!。

节流

代码语言:javascript复制
function throttle(fn, delay = 2000) {
  let canRun = true;
  return function () {
    if (!canRun) return;
    canRun = false;
    fn.apply(this, arguments);
    setTimeout(function () {
      canRun = true;
    }, delay);
  };
}

/* ---------- */

async function testFunc() {
  console.time('x');
  console.log('Hello, World0!');
  var test = throttle(function () {
    console.log('Hello, World1!');
    console.timeEnd('x');
  }, 5000);
  test();
  await new Promise((resolve) => {
    setTimeout(() => resolve(), 1000);
  });
  test();
  await new Promise((resolve) => {
    setTimeout(() => resolve(), 1000);
  });
  test();
  console.log('Hello, World2!');
}
testFunc();
// 第一次才有效,严格意义立即打印一次 Hello, World1!。

fetch/ajax/axios/XHR

代码语言:javascript复制
/* ----- Ajax ----- */
$.ajax({
  url: '/test',
  success: function (result) {
    console.log(result);
  }
});

$.ajax({
  url: '/test',
  method: 'POST',
  success: function (result) {
    console.log(result);
  }
});

$.ajax({
  url: '/test',
  data: { a: 10 },
  success: function (result) {
    console.log(result);
  },
  error: function (xhr, status, error) {
    console.log(error);
  }
});

$.ajax({
  url: '/test',
  headers: { contentType: 'application/json' },
  method: 'POST',
  data: JSON.stringify({ a: 10 }),
  success: function (result) {
    console.log(result);
  }
});

$.get(url, data, callback); // querystring
$.post(url, data, callback); // x-www-form-urlencoded




/* ----- Fetch ----- */
fetch(url, {
  headers: {
    'content-type': 'application/x-www-form-urlencoded'
  },
  method: 'POST',
  body: 'a=1&b=2&c[]=a&c[]=b'
})
  .then((res) => res.json())
  .then((data) => console.log(res))
  .catch((e) => {});

fetch(url, {
  headers: {
    'content-type': 'application/json'
  },
  method: 'POST',
  body: JSON.stringify({ a: 100 })
})
  .then((res) => res.json())
  .then((data) => console.log(res))
  .catch((e) => {});



/* ----- Axios ----- */
axios({
  url: 'http://localhost',
  method: 'POST',
  data: { a: 1 }
}).then((res) => console.log(res.data));

axios({
  url: 'http://localhost',
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  data: 'a=1&b=2&c[]=a&c[]=b'
}).then((res) => console.log(res.data));

axios.post(url, data).then(callback);



/* ----- XHR-XMLHttpRequestAjax ----- */
function XMLHttpRequestAjax(method, url, callback, data, flag) {
  var xhr;
  flag = flag || true;
  method = method.toUpperCase();
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveXObject('Microsoft.XMLHttp');
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      callback(xhr.responseText);
    }
  };

  if (method == 'GET') {
    var date = new Date(),
      timer = date.getTime();
    xhr.open('GET', url   '?'   data   '&timer'   timer, flag);
    xhr.send();
  } else if (method == 'POST') {
    xhr.open('POST', url, flag);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(data);
  }
}

Base64

代码语言:javascript复制
static base64Encode(str: string): string {
  return Buffer.from(str, 'utf-8').toString('base64');
}

static base64Decode(str: string): string {
  return Buffer.from(str, 'base64').toString('utf8');
}

0 人点赞