26 Ekim 2020 Pazartesi

Polyfill Nedir

Giriş
Açıklaması şöyle
A polyfill is code which simulates modern JavaScript features missing in older browsers.
Örnek
Şöyle yaparız
function filter(array, condition) {
  result = []
  for (element of array)
    if condition(element)
      result.push(element)
  return result
}

if (Array does not have filter function)
  Array.filter = filter

6 Ekim 2020 Salı

TypeScript Function Tanımlama

Function Tanımlama
Parametrenin tipi parametre isminden sonra myparameter : string şeklinde yazılır. Function sonuç dönüyorsa yine kapanış parantezinden sonra ): string şeklinde yazılır.

Örnek - const f = {...} Şeklinde
Şöyle yaparız. string veya null dönebilir.
const getErrorTextIfPresent = (r: ValidationResult): string | null => {
  return r.isValid ? null : r.errorText;
}
Örnek
Şöyle yaparız
function reverse(word:string):string{
  ...
}
Örnek  - Optional Parametreler
Optional parametrelerle tanımlamak için şöyle yaparız
function greet(firstName?: string, lastName?: string) {
  if (fistName && lastName) console.log(`Hello, ${firstName} ${lastName}!`)
  else console.log('Hello, World!')
}

greet('John', 'Doe') // Hello, John Doe!
greet() // Hello, World!
greet('John') // Invalid
Örnek - Generics
Şöyle yaparız. Nesnenin üye alanlarının ismini değiştirir. Alan ismi başına "old" getirilir.
type PrefixAll<T, P extends string>  = {
    [K in keyof T & string as `${P}${K}`]: T[K]
}

function prefixProperties<T, P extends string>(obj: T, prefix: P): PrefixAll<T, P> {
    let out = {} as Record<string, unknown>;
    for (let propt in obj) {
        out[prefix + propt] = obj[propt];
      }
    return out as PrefixAll<T, P>;
}

let x : { num: number, date: Date } = { ... };
let y = prefixProperties(x, 'old');

y.olddate
y.oldnum
Örnek
Prototype ile tanımlamak için şöyle yaparız
type Greet = {
     (firstName: string, lastName: string): void;
     (): void;
};
const greet: Greet = (firstName?: string, lastName?: string) => {
  if (firstName && lastName) console.log(`Hello, ${firstName} ${lastName}!`)
  else console.log('Hello, World!')
};

greet('John', 'Doe'); // Hello, John Doe!
greet(); // Hello, World!
greet('John'); // Hello World!

Map Sınıfı

Giriş
Map'e hem bir alan olarak, hem de string olarak ile erişebiliriz.
var myMap = {a: 1, b: 2}
var firstWay = myMap.a
var secondWay = myMap['a']
String bir değişken içinde de olabilir.
property = 'a'
myMap[property] // results in 1
Eğer alan ismi farklı yorumlanmaya açıksa dikkatli olmak gerekir.
obj["a-b"]; // ok
obj.a-b;    // fail! Parsed as `(obj.a) - b`
get metodu
Açıklaması şöyle
But note, it is hashing based on identity, i.e. ===...
Şöyle yaparız
> m1 = new Map([['a', 1]])
Map { 'a' => 1 }
> m2 = new Map()
Map {}
> m2.set(m1, 3)
Map { Map { 'a' => 1 } => 3 }
> m2.get(m1)
3
Ancak şöyle yaparsak çalışmaz
> m2.get(new Map([['a',1]]))
undefined

27 Ağustos 2020 Perşembe

Promise Sınıfı

Giriş
Constructor içindeki metodu çalıştırdıktan sonra resolve veya reject çağrısı yapılır. Bu çağrı sonucunda then() ile takılan metodlar asenkron olarak çağrılır.

then() metodu iki tane parametre alır. Bunlara success() ve error() diyelim. Eğe resolve() çağrılırsa succees() tetiklenir, reject() çağrılırsa error() tetiklenir

Not : PromiseJobs Queue yazısına bakabilirsiniz.
constructor - resolve function
Açıklaması şöyle
Promise constructor runs synchronously
Örnek
Belirtilen işi gecikme ile çalıştırmak için şöyle yaparız.
const delay = ms => new Promise(res => setTimeout(res, ms));
constructor - resolve function + reject function
Açıklaması şöyle.
The Promise receives two callbacks in constructor function: resolve and reject. These callbacks inside promises provide us with fine-grained control over error handling and success cases. The resolve callback is used when the execution of promise performed successfully and the reject callback is used to handle the error cases.
Örnek
Şöyle yaparız. Eğer resolve() metodu çağrılırsa promise'in then() metodunun success() parametresi tetiklenir. Eğer reject() metodu çağrılırsa, then() metodunun error() parametresi
var p1 = new Promise(function(resolve, reject) {
  var num = Math.random();
  if (num < .5) {
    resolve(num);
  } else {
    reject(num);
  }
});
Örnek
Eğer resolve veya reject'in bir tanesi çalışmazsa hata alırız. Açıklaması şöyle.
If you have promises that occasionally don't resolve or reject and that's not the way they are supposed to work (which it usually isn't), then you just have to fix that.
Elimizde şöyle bir kod olsun. Burada parametre olarak 5 verilence Promise ne resolve() ne de reject() metodunu çağırıyor ve hata alıyoruz.
class Utils {
 static async thisFunctionOnlyResolvesWhenPassed2AndNeverRejects(number: number){
   return new Promise((resolve, reject) => {
     if(number === 2) {
       resolve('ok')
     }
   })
 }
}

console.log(await Utils.thisFunctionOnlyResolvesWhenPassed2AndNeverRejects(2))
// this will print "ok" because 2 is passed and the promise is resolved

console.log(await Utils.thisFunctionOnlyResolvesWhenPassed2AndNeverRejects(5))
// this will crash the program silently 
all metodu
Parametre olarak verilen tüm işlerin bitmesini bekler. Daha sonra genellikle then() ile devam edilir.
Örnek
Şöyle yaparız
const promises = ...; // Array of Promises
Promise.all(promises).then( response => {
  // ... 
});
Örnek
Şöyle yaparız.
Promise.all(requests)
  .then((responses) => {
    console.log('done');
    console.log(responses);
  });
catch metodu
İşlev olarak şöyle.
.then(null, onRejected)
Hatta eski kütüphanelerde şöyleydi.
Promise.prototype.catch = function (onRejected) {
  return this.then(null, onRejected);
};
race metodu
Açıklaması şöyle. İlk resolve() veya reject() edilen şeyi döner.
The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.
Örnek
Elimizde şöyle bir kod olsun
function rejectT(t) {
  // create potential error here for better opportunity at stack trace
  let e = new Error("Promise timed out");
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(e);
      reject(e);
    }, t);
  });
}

function timeout(p, t = 5000) {
    return Promise.race([p, rejectT(t)]);
}
Kullanmak için şöyle yaparız
timeout(fn()).then(...).catch(...);
resolve metodu
Bitmiş bir Promise döner.
Örnek
Elimizde şöyle bir kod olsun
var functArray = [
  function() {
    console.log("function1 executed");
  },
   function() {
    console.log("function2 executed");
  },
    function() {
    console.log("function3 executed");
  },
    function() {
    console.log("function4 executed");
  }];
Şöyle yaparız.
funcArray.reduce((p, fn) => {
    return p.then(fn => {
        fn();
    });
}, Promise.resolve());
then metodu
İmzası şöyle. Promise hazır olunca çalışır.
.then(onFullfilled, onRejected)
Örnek
Reject metodu vermek istemezsek şöyle yaparız.
p.then(function success(res) {
  successes++;
  console.log("*Success:* " + res)
})
Örnek
Success() ve Reject() metodlarını vermek istersek şöyle yaparız.
p1.then(function success(res) {
  successes++;
  console.log("*Success:* " + res);
  }, function error(error) {
    errors++;
    console.log("*Error:* " + error);
});
Örnek
Success() ve Reject() metodlarını vermek istersek şöyle yaparız.
p1.then(function success(res) {
  successes++;
  console.log("*Success:* " + res);
  }, function error(error) {
    errors++;
    console.log("*Error:* " + error);
});
then metodu ve Promise Chaining
then() metodu arka arkaya bağlanabilir.
Örnek
Şöyle yaparız
promıse.then(...).then(...).catch(...)
Örnek
Elimizde şöyle bir soru olsun
You have three functions, which are all asynchronous:

- loadReport(id) which fetches the definition of a report
- runReport(report) which runs the report and returns a path to a PDF output file
- sendReport(filePath) which mails the file to subscribers and returns true if succeeded

Write code that executes a report using these three functions and shows alert if everything went well. Each of these functions can throw an exception. How would you handle it?
Şöyle yaparız
 loadReport(id)
  .then(report => runReport(report))
  .then(outputPath => sendReport(outputPath))
  .then(completed => alert(completed ? 'Done!' : 'Bad monkey!'))
  .catch(error => alert(error.message))