DOM
  • Bir öğenin başka birinin kapsayıcısı olup olmadığını kontrol etme
    const isContains = (child, parent) => parent.contains(child);
  • Ögenin focus durumunu kontrol etme
    const hasFocus = ele => (ele === document.activeElement);
  • Dokunma olaylarının desteklenip desteklenmediğini kontrol etme
    const touchSupported = () => ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
  • İnternet explorer tarayıcısını algılama
    const isIE = !!document.documentMode;
    
    
  • MacOS tarayıcısını algıla
    const isMacBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
  • Bir elemanın tüm kardeşlerini almak
    const siblings = ele => [].slice.call(ele.parentNode.children).filter((child) => (child !== ele));
  • Seçili metni almak
    const getSelectedText = () => window.getSelection().toString();
  • Bir önceki sayfaya geri dönme
    history.back();
    
    // Ya da
    history.go(-1);
  • Bir elemanı gizleme
    // Kullanım durumuna göre seçmek gerek display eleman kaldırıldığında boşluk bırakmaz, visibility de ise boşluğu kalır
    const hide = ele => ele.style.display = 'none';
    
    // Ya da
    const hide = ele => ele.style.visibility = 'hidden';
  • Bir elemanın sonrasına yeni bir öğe ekleme
    const addAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling);
    
    // Ya da
    const addAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele);
  • Bir elemanın öncesine yeni bir öğe ekleme
    const addBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle);
    
    // Ya da
    const addBefore = (ele, anotherEle) => anotherEle.insertAdjacentElement('beforebegin', ele);
  • Bir elemanın sonrasına html ekleme
    const addHtmlAfter = (html, ele) => ele.insertAdjacentHTML('afterend', html);
  • Bir elemanın öncesine html ekleme
    const addHtmlBefore = (html, ele) => ele.insertAdjacentHTML('beforebegin', html);
  • Sayfayı başka bir url'e yönlendirme
    const goTo = url => location.href = url;
  • Mevcut sayfayı yenileme
    const reload = () => location.reload();
    
    // Ya da
    const reload = () => (location.href = location.href);
  • Bir elemanı başka bir elaman ile değiştirme
    const replace = (ele, newEle) => ele.parentNode.replaceChild(newEle, ele);
  • Sayfanın en üstüne çıkma
    const goToTop = () => window.scrollTo(0, 0);
  • Gizli bir elamanı görünür yapmak
    const show = ele => ele.style.display = '';
  • Verilen bir metinden html'yi çıkartma
    const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
  • bir elamana Göster/Gizle yapmak
    const toggle = ele => (ele.style.display = (ele.style.display === 'none') ? 'block' : 'none');
Diziler
  • Dizinin boş olup olmadığını kontrol etmek
    // `arr` örnek bir dizi
    const isEmpty = arr => !Array.isArray(arr) || arr.length === 0;
    
    // Örnekler
    isEmpty([]);            // true
    isEmpty([1, 2, 3]);     // false
  • Diziyi kopyalama
    // `arr` örnek bir dizi
    const clone = arr => arr.slice(0);
    
    // Ya da
    const clone = arr => [...arr];
    
    // Ya da
    const clone = arr => Array.from(arr);
    
    // Ya da
    const clone = arr => arr.map(x => x);
    
    // Ya da
    const clone = arr => JSON.parse(JSON.stringify(arr));
    
    // Ya da
    const clone = arr => arr.concat([]);
  • İki Diziyi karşılaştırma (sadece elamanları karşılaştırma)
    // `a` ve `b` birer dizi
    const isEqual = (a, b) => JSON.stringify(a.sort()) === JSON.stringify(b.sort());
    
    // Örnekler
    isEqual([1, 2, 3], [1, 2, 3]);      // true
    isEqual([1, 2, 3], [1, 3, 2]);      // true
    isEqual([1, 2, 3], [1, '2', 3]);    // false
    
    
  • İki Diziyi karşılaştırma (birebir)
    // `a` ve `b` birer dizi
    const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
    
    // Ya da
    const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
    
    // Örnekler
    isEqual([1, 2, 3], [1, 2, 3]);      // true
    isEqual([1, 2, 3], [1, '2', 3]);    // false
  • Dizideki elemanlardan istenen key'e göre yeni obje oluşturma
    const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
    
    // Örnek
    toObject(
        [
            { id: '1', isim: 'Hamza', yas: 25 },
            { id: '2', isim: 'Kaya', yas: 27 },
            { id: '3', isim: 'Sedat', yas: 29 },
        ],
        'id'
    );
    /* 
    {
        '1': { id: '1', isim: 'Hamza', yas: 25 },
        '2': { id: '2', isim: 'Kaya', yas: 27 },
        '3': { id: '3', isim: 'Sedat', yas: 29 },
    }
    */
    
  • Dizideki tüm elemanları sayıya çevirme
    const toNumbers = arr => arr.map(Number);
    
    // Ya da
    const toNumbers = arr => arr.map(x => +x);
    
    // Örnek
    toNumbers(['2', '3', '4']);     // [2, 3, 4]
  • Dizideki tüm elemanları istenilen key'e göre gruplandırma
    const groupBy = (arr, key) => arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {});
    
    // Örnek
    groupBy([
        { marka: 'audi', model: 'q8', yil: '2019' },
        { marka: 'audi', model: 'rs7', yil: '2020' },
        { marka: 'ford', model: 'mustang', yil: '2019' },
        { marka: 'ford', model: 'explorer', yil: '2020' },
        { marka: 'bmw', model: 'x7', yil: '2020' },
    ], 'marka');
    
    /*
    {
      "audi": [
        { "marka": "audi", "model": "q8", "yil": "2019" },
        { "marka": "audi", "model": "rs7", "yil": "2020" }
      ],
      
      "ford": [
        { "marka": "ford", "model": "mustang", "yil": "2019" },
        { "marka": "ford", "model": "explorer", "yil": "2020" }
      ],
    
      "bmw": [
        { "marka": "bmw", "model": "x7", "yil": "2020" }
      ]
    }
    */
    
  • Dizideki tüm elemanları istenilen key'e göre gruplandırıp, eleman sayılarını öğrenme
    const countBy = (arr, prop) => arr.reduce((prev, curr) => (prev[curr[prop]] = ++prev[curr[prop]] || 1, prev), {});
    
    // Örnek
    countBy([
        { marka: 'audi', model: 'q8', yil: '2019' },
        { marka: 'audi', model: 'rs7', yil: '2020' },
        { marka: 'ford', model: 'mustang', yil: '2019' },
        { marka: 'ford', model: 'explorer', yil: '2020' },
        { marka: 'bmw', model: 'x7', yil: '2020' },
    ], 'marka');
    
    // { 'audi': 2, 'ford': 2, 'bmw': 1 }
  • Dizide istenilen elemanın kaç defa bulunduğunu öğrenme
    const lengthBy = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
    
    // Örnekler
    lengthBy([2, 1, 3, 3, 2, 3], 2);                // 2
    lengthBy(['a', 'b', 'a', 'c', 'a', 'b'], 'a');  // 3
  • Dizideki tüm elemanların kaç defa bulunduğunu öğrenme
    const lengthAll = arr => arr.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {});
    
    // Örnekler
    lengthAll([2, 1, 3, 3, 2, 3]);               // { '1': 1, '2': 2, '3': 3 }
    lengthAll(['a', 'b', 'a', 'c', 'a', 'b']);   // { 'a': 3, 'b': 2, 'c': 1 }
  • Kümülatif toplam dizisi oluşturma
    const kumulatif = arr => arr.map((sum => value => sum += value)(0));
    
    // Ya da
    const kumulatif = arr => arr.reduce((a, b, i) => i === 0 ? [b] : [...a, b + a[i - 1]], []);
    
    // Ya da
    const kumulatif = arr => arr.reduce((a, b, i) => i === 0 ? [b] : [...a, b + a[i - 1]], 0);
    
    // Örnek
    kumulatif([1, 2, 3, 4]);   // [1, 3, 6, 10]
    // 1             = 1
    // 1 + 2         = 3
    // 1 + 2 + 3     = 6
    // 1 + 2 + 3 + 4 = 10
  • Verilen aralıkta sayı dizisi oluşturma
    const aralik = (min, max) => [...Array(max - min + 1).keys()].map(i => i + min);
    
    // Ya da
    const aralik = (min, max) => Array(max - min + 1).fill(0).map((_, i) => min + i);
    
    // Ya da
    const aralik = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i);
    
    // Örnek
    aralik(5, 10);   // [5, 6, 7, 8, 9, 10]
  • Diziden istenilen en yakın sayıyı bul
    // `arr` dizisinde `n` e en yakın eleman
    const enYakini = (arr, n) => arr.reduce((prev, curr) => Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev);
    
    // Ya da
    const enYakini = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0];
    
    // Örnek
    enYakini([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50);   // 33
  • Dizideki en uzun kelimeleri ya da en uzun kelimenin uzunluğunu bulma
    const longStrings = arr => arr.filter(i => i.length === Math.max(...(arr.map(el => el.length))))
    const longStringLength = s => Math.max(...(s.map(el => el.length)));
    
    // Örnek
    longStrings(['hamza', 'kaya', 'sedat', 'javascript']);  // javascript
    longStringLength(['hamza', 'kaya', 'sedat', 'javascript']);  // 10
  • Sayı dizisindeki en büyük elemanı bulma
    const max = arr => Math.max(...arr);
  • Sayı dizisindeki en küçük elemanı bulma
    const min = arr => Math.min(...arr);
  • İç içe dizilerdeki tüm elemanlardan yeni dizi oluşturma
    const flat = arr => [].concat.apply([], arr.map(a => Array.isArray(a) ? flat(a) : a));
    // Ya da
    const flat = arr => arr.reduce((a, b) => Array.isArray(b) ? [...a, ...flat(b)] : [...a, b], []);
    
    // Ya da
    // Browser destekliyormu kontrol etmek için https://caniuse.com/#feat=array-flat
    const flat = arr => arr.flat();
    
    // Örnek
    flat(['kedi', ['aslan', 'kaplan']]);   // ['kedi', 'aslan', 'kaplan']
  • Sayı dizisindeki tüm elemanların ortalamasını bulma
    const ortalama = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
  • İki dizinin kesişimini / ortak elemanları bulma
    const ortakElamanlar = (a, ...arr) => [...new Set(a)].filter(v => arr.every(b => b.includes(v)));
    
    // Örnekler
    ortakElamanlar([1, 2, 3], [2, 3, 4, 5]);               // [2, 3]
    ortakElamanlar([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]);    // [3]
    
    
  • Sayı Dizideki tüm elemanların toplamını bulma
    const sum = arr => arr.reduce((a, b) => a + b, 0);
  • Dizideki tekrar eden elemanları silme (alt dizileri etkilemeden)
    const unique = arr => [...new Set(arr)];
    
    // Ya da
    const unique = arr => arr.filter((el, i, array) => array.indexOf(el) === i);
    
    // Ya da
    const unique = arr => arr.reduce((acc, el) => acc.includes(el) ? acc : [...acc, el], []);
  • Birden çok diziyi birleştirme , tekrar eden elaman olmadan
    const union = (...arr) => [...new Set(arr.flat())];
    
    // Örnek
    union([1, 2], [2, 3], [3], [1,2,3,4]);     // [1, 2, 3, 4]
  • İki diziyi birleştirme
    // birleştir ama tekrar eden elemanları silme
    const merge = (a, b) => a.concat(b);
    // Ya da
    const merge = (a, b) => [...a, ...b];
    
    // birleştir ve tekrar eden elemanları sil
    const merge = (a,b) => [...new Set(a.concat(b))];
    // Ya da
    const merge = (a,b) => [...new Set([...a, ...b])];
  • Diziyi istenilen kurala uyan/uymayan şeklinde ayırma
    const kuralKontrol = (arr, kural) => arr.reduce((acc, i) => (acc[kural(i) ? 0 : 1].push(i), acc), [[], []]);
    
    // Örnek, 2 ye bölünebilme durumlarına göre
    kuralKontrol([1, 2, 3, 4, 5], n => n % 2);     // [[2, 4], [1, 3, 5]]
  • Dizideki yanlış ya da hata elemanlarını silme
    const hatalilariFiltrele = arr => arr.filter(Boolean);
    
    // Örnek
    hatalilariFiltrele([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]); // ['a string', true, 5, 'another string']
  • Dizinin elemanlarını rastgele sıralama
    const rastgele = arr => arr.map(a => ({ sort: Math.random(), value: a })).sort((a, b) => a.sort - b.sort).map(a => a.value);
    
    // Ya da
    const rastgele = arr => arr.sort(() => .5 - Math.random());
    
    // Örnek
    rastgele([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);   // [9, 1, 10, 6, 8, 5, 2, 3, 7, 4]
  • Dizinin elemanlarını küçükten büyüğe sıralama
    const sirala = arr => arr.sort((a, b) => a - b);
    
    // Örnek
    sirala([1, 5, 2, 0, 4, 3, -1]);      // [-1, 0, 1, 2, 3, 4, 5]
  • Bir diziyi istenilen eleman sayısına göre gruplandırma
    const grupla = (arr, s) => arr.reduce((acc, e, i) => (i % s ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []);
    
    // Örnekler
    grupla([1, 2, 3, 4, 5, 6, 7, 8], 3);        // [[1, 2, 3], [4, 5, 6], [7, 8]]
    grupla([1, 2, 3, 4, 5, 6, 7, 8, 9], 4);     // [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
  • Matrisde satır ve sütün yer değiştirme
    const degistir = matris => matris[0].map((col, i) => matris.map(row => row[i]));
    
    // Ya da
    const degistir = matris => matris[0].map((col, c) => matris.map((row, r) => matris[r][c]));
    
    // Ya da
    const degistir = matris => matris.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), []);
    
    // Örnek
    degistir([             // [
        [1, 2, 3],          //      [1, 4, 7],
        [4, 5, 6],          //      [2, 5, 8],
        [7, 8, 9],          //      [3, 6, 9],
    ]);                     //  ]
  • Dizinin tüm alt dizilerini sırasına göre yeni dizi oluşturma
    const unzip = arr => arr.reduce((acc, c) => (c.forEach((v, i) => acc[i].push(v)), acc), Array.from({ length: Math.max(...arr.map(a => a.length)) }, (_) => []));
    
    // Örnek
    unzip([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]);  // [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]]
    
    /*
        a     1
         b   2
          c 3
          d 4
          e 5
    */
    
  • Birden çok diziyi, elemanların sırasına göre birleştirme
    const zip = (...arr) => Array.from({ length: Math.max(...arr.map(a => a.length)) }, (_, i) => arr.map(a => a[i]));
    
    // Örnek
    zip(['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]);   // [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]
    
    /*
    Fermuar gibi teker teker birleştirme
            a 1
            b 2
           c   3
          d     4
         e       5
    */
    
Fonksiyon
  • Bir değerin fonksiyon olup olmadığını kontrol edin
    const isFunction = v => ['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes(Object.prototype.toString.call(v));
    
    // Örnekler
    isFunction(function() {});          // true
    isFunction(function*() {});         // true
    isFunction(async function() {});    // true
  • Bir değerin generator fonksiyon olup olmadığını kontrol edin
    const isGeneratorFunction = v => Object.prototype.toString.call(v) === '[object GeneratorFunction]';
    
    // Örnekler
    isGeneratorFunction(function() {});     // false
    isGeneratorFunction(function*() {});    // true
  • Bir değerin asenkron fonksiyon olup olmadığını kontrol edin
    const isAsyncFunction = v => Object.prototype.toString.call(v) === '[object AsyncFunction]';
    
    // Örnekler
    isAsyncFunction(function() {});         // false
    isAsyncFunction(function*() {});        // false
    isAsyncFunction(async function() {});   // true
  • Birden çok fonksiyonu birleştirip yeni fonksiyon oluşturma
    const soldanSaga = (...fns) => x => fns.reduce((y, f) => f(y), x);
    const sagdanSola = (...fns) => x => fns.reduceRight((y, f) => f(y), x);
    
    
    // Örnek
    const lowercase = str => str.toLowerCase();
    const capitalize = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
    
    const fn1 = soldanSaga(lowercase, capitalize);
    const fn2 = sagdanSola(capitalize, lowercase);
    
    
    fn1('heLLO WoRlD') // 'Hello world';
    fn2('heLLO WoRlD') // 'Hello world';
  • Currying fonksiyon
    const curry = (fn, ...args) => fn.length <= args.length ? fn(...args) : curry.bind(null, fn, ...args);
    
    // Örnek
    const topla = (a, b, c) => a + b + c;
    curry(topla)(1)(2)(3);    // 6
    curry(topla)(1, 2, 3);    // 6
    curry(topla, 1)(2, 3);    // 6
    curry(topla, 1)(2)(3);    // 6
    curry(topla, 1, 2)(3);    // 6
    curry(topla, 1, 2, 3);    // 6
  • Bir fonksiyonun argümanlarını ters çevirme
    // Bağımsız değişkenlerin sırasını tersine çevirin
    const flip = fn => (...args) => fn(...args.reverse());
    
    // İkili fonksiyonlar için
    const flip = fn => (b, a) => fn(a, b);
    
    // Ya da curried fonksiyonlar için
    const flip = fn => b => a => fn(a)(b);
    
    // Örnek
    const isParent = (parent, child) => parent.children.includes(child);
    const isChild = flip(isParent);
  • Mantıksal XOR Kapısı
    // XOR Kapısı, girişindeki işaretler birbirinden farklı olduğu zaman çıkış olarak 1 verir, diğer tüm hallerde 0 verir. 
    // XOR kapısının Boole Cebiri eşitliği; A xor B = A'B+AB' şeklindedir.
    
    const xor = (a, b) => (a && !b) || (!a && b);
    
    // Ya da
    const xor = (a, b) => !(!a && !b) && !(a && b);
    
    // Ya da
    const xor = (a, b) => Boolean(!a ^ !b);
    
    // Örnekler
    xor(true, true);        // false
    xor(false, false);      // false
    xor(true, false);       // true
    xor(false, true);       // true
  • Hatırlayıcı / Memoize Fonksiyon
    const memoize = fn => ((cache = {}) => arg => cache[arg] || (cache[arg] = fn(arg)))();
    
    // Örnek
    // Fibonacci fonksiyonu
    const fibonacci = memoize(n => n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2));
    
    fibonacci(1);    // 1
    fibonacci(2);    // 1
    fibonacci(3);    // 2
    fibonacci(4);    // 3
    fibonacci(5);    // 5
    fibonacci(6);    // 8
  • Fonksiyondan yeni fonksiyon türetmek (sabit değişkenli)
    const turet = (fn, ...a) => (...b) => fn(...a, ...b);
    
    // Örnek
    const topla = (x, y) => x + y;
    const ikiFazlasi  = turet(topla, 2);
    ikiFazlasi(8);     // 10
Hesaplama
  • Fibonacci hesaplama
    const fibo = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = fibo(n - 1, memo) + fibo(n - 2, memo)));
    
    // Örnekler
    fibo(1);    // 1
    fibo(2);    // 1
    fibo(3);    // 2
    fibo(4);    // 3
    fibo(5);    // 5
    fibo(6);    // 8
  • Obeb / Ebob hesaplama
    // 2 sayı ile hesaplamak için
    const obeb = (a, b) => b === 0 ? a : obeb(b, a % b);
    
    // 2 den fazla sayı ile hesaplamak için
    const obeb = (...arr) => { const min = Math.min(...arr); for (let obeb = min; obeb > 1; obeb--) { let bolunebilme = true; for (let j = 0; j < arr.length; j++) {if (arr[j] % obeb !== 0) { bolunebilme = false; break; } } if (bolunebilme){ return obeb } } return 1}
    
    // Örnek
    obeb(10, 15);    // 5
  • Ortalama hesaplama
    const ortalama = (...args) => args.reduce((a, b) => a + b) / args.length;
    
    // Örnek
    ortalama(3,5,7,9);    // 6
  • Faktöriyel hesaplama
    const faktoriyel = n => n <= 1 ? 1 : n * faktoriyel(n - 1);
    
    // Örnekler
    faktoriyel(2);   // 2
    faktoriyel(3);   // 6
    faktoriyel(4);   // 24
    faktoriyel(5);   // 120
    faktoriyel(6);   // 720
  • Limitsiz toplama
    const topla = (...args) => args.reduce((a, b) => a + b);
    
    // Örnek
    topla(1, 2, 3, 4);    // 10
  • İki değer arasında bir sayı üretme
    // verilen ilk değer , min ve max değerlerinin arasındaysa o değeri alır, 
    // diğer durumlarda en fazla ya da en az olarak verilen değeri döner
    const uret = (deger, min = 0, max = 1) => Math.max(min, Math.min(max, deger));
    
    // Örnek
    uret(199, 10, 25);     // 25
  • Bir sayıyı eşdeğer karakterlere dönüştürme
    const toChar = n => `${n >= 26 ? toChar(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`;
    
    // Örnekler
    toChar(0);     // A
    toChar(1);     // B
    toChar(25);    // Z
    
    toChar(26);     // AA
    toChar(27);     // AB
    toChar(51);     // AZ
    
    toChar(701);   // ZZ
    toChar(702);   // AAA
    toChar(703);   // AAB
  • Dereceleri radyana dönüştürme , ya da tam tersi
    const dereceRadyan = num => (num * Math.PI) / 180.0;
    
    const radyanDerece = num => num * 180 / Math.PI;
  • Sayının rakamlarından dizi oluşturma
    const rakamlari = n => `${n}`.split('').map(v => parseInt(v));
    
    // Örnek
    rakamlari(1453);    // [1, 4, 5, 3]
  • Bir sayının istenilen uzunluktan kısaysa, ön ek olarak 0 ekletme
    const sifirOnEk = (sayi, uzunluk) => (sayi / Math.pow(10, uzunluk)).toFixed(uzunluk).substr(2);
    
    // Ya da
    const sifirOnEk = (sayi, uzunluk) => `${Array(uzunluk).join('0')}${sayi}`.slice(-uzunluk);
    
    // Ya da
    const sifirOnEk = (sayi, uzunluk) => String(sayi).padStart(uzunluk, '0');
    
    
    // Örnek, 5ten kısaysa
    sifirOnEk(42, 5);     // '00042'
  • Bir sayıyı belirli sayıda basamağa yuvarlama
    const yuvarla = (n, basamak = 0) => Number(`${Math.round(`${n}e${basamak}`)}e-${basamak}`);
    
    // Örnekler
    yuvarla(0.987654321, 2)     // 0.99
    yuvarla(0.987654321, 3)     // 0.988
    yuvarla(0.987654321, 4)     // 0.9877
    yuvarla(0.987654321, 5)     // 0.98765
  • Bir sayının basamaklarını kesmek
    const kes = n => ~~n;
    
    // Örnekler
    kes(25.198726354);         // 25
    kes(-25.198726354);        // -25
  • Bir sayıyı, yuvarlamadan, belirli sayıda ondalık basamağa kadar kısaltmak
    const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\\d+(?:\.\\d{0,${fixed}})?`))[0];
    
    // Örnekler
    toFixed(25.198726354, 1);       // 25.1
    toFixed(25.198726354, 2);       // 25.19
    toFixed(25.198726354, 3);       // 25.198
    toFixed(25.198726354, 4);       // 25.1987
    toFixed(25.198726354, 5);       // 25.19872
    toFixed(25.198726354, 6);       // 25.198726
Obje
  • İki objenin aynı olup olmadığını kontrol etme
    const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]));
    
    // Örnekler
    isEqual({ foo: 'bar' }, { foo: 'bar' });    // true
    isEqual({ foo: 'bar' }, { bar: 'foo' });    // false
  • Anahtar ve değer çiftlerinden bir obje oluşturma
    const toObj = arr => Object.fromEntries(arr)
    //ya da
    const toObj = arr => arr.reduce((a, c) => ((a[c[0]] = c[1]), a), {});
    
    
    // Örnek
    toObj([['a', 1], ['b', 2], ['c', 3]]);      // { a: 1, b: 2, c: 3 }
  • Objeden istenen anahtar değeri ile dizi oluşturma
    const ayikla = (objs, key) => objs.map(obj => obj[key]);
    
    // Örnek
    ayikla([
        { isim: 'Ahmet', yas: 20 },
        { isim: 'Mehmet', yas: 25 },
        { isim: 'Ali', yas: 30 },
    ], 'isim');         // ['Ahmet', 'Mehmet', 'Ali']
  • Objeden yol üzerinden istenen değeri alma
    const getVal = (path, obj) => path.split('.').reduce((acc, c) => acc && acc[c], obj);
    
    // Örnek
    getVal('a.b', { a: { b: 'Deneme' } });   // 'Deneme';
  • Anahtar ile değerleri ters çevirme
    const tersCevir = obj => Object.keys(obj).reduce((res, k) => Object.assign(res, {[obj[k]]: k}), {});
    
    // Örnek
    tersCevir({ a: '1', b: '2', c: '3' });     // { 1: 'a', 2: 'b', 3: 'c' }
  • Objeden istenen anahtar değerlerini çıkartma (omit)
    const omit = (obj, keys) => Object.keys(obj).filter(k => !keys.includes(k)).reduce((res, k) => Object.assign(res, {[k]: obj[k]}), {});
    
    // Örnek
    omit({a: '1', b: '2', c: '3'}, ['a', 'b']);     // { c: '3' }
  • Objeden istenen anahtar değerlerini alma (pick)
    const pick = (obj, keys) => Object.keys(obj).filter(k => keys.includes(k)).reduce((res, k) => Object.assign(res, {[k]: obj[k]}), {});
    
    // Örnek
    pick({ a: '1', b: '2', c: '3' }, ['a', 'b']);   // { a: '1', b: '2' }
Random
  • Boolean değer üretme
    const randomBoolean = () => Math.random() >= 0.5;
  • Verilen aralıkta float değer üretme
    const randomFloat = (min, max) => Math.random() * (max - min) + min;
  • HEX değeri oluşturma
    const randomHEX = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
    
    // Ya da
    const randomHEX = () => `#${(~~(Math.random()*(1<<24))).toString(16)}`;
  • Verilen aralıkta sayısal değer üretme
    const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
  • IP adresi oluşturma
    const randomIp = () => Array(4).fill(0).map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0)).join('.');
    
    // Örnek
    randomIp();     // 175.89.174.131
  • Verilen karakterlerden yazı üretme
    const generateString = (len, chars) => Array(len).fill('').map((v) => chars[Math.floor(Math.random() * chars.len)]).join('');
    
    // Örnek
    generateString(10, 'abc'); // "abccbbaabc"
  • İstenilen uzunlukta yazı üretme
    const generateString = length => Array(length).fill('').map((v) => Math.random().toString(36).charAt(2)).join('');
  • rastgele uuid üretme
    const uuid = (a) => a ? (a ^ Math.random() * 16 >> a / 4).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid);
  • İstenilen aralıkta, istenilen miktarda sayı dizisi üretme
    const randomArrayInRange = (min, max, n) => Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
    
    // Örnek
    randomArrayInRange(1, 100, 10);     // [11, 82, 41, 35, 76, 83, 43, 15, 60, 54]
  • Diziden rastgele bir eleman getirme
    const randomItem = arr => arr[(Math.random() * arr.length) | 0];
    
    
String
  • İlk harfi büyütmek
    const ilkHarfiBuyut = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
    
    // Örnek
    ilkHarfiBuyut('hello world');      // 'Hello world'
  • Dosya yolunun doğru olup olmadığını kontrol etme
    const truePath = path => !/^([a-z]+:)?[\\/]/i.test(path);
    
    // Örnekler
    truePath('/foo/bar/baz');         // false
    truePath('C:\\foo\\bar\\baz');    // false
    truePath('foo/bar/baz.txt');      // true
    truePath('foo.md');               // true
  • Palindrom olup olmadığını kontrol edin
    // Palindrom, tersten okunuşu da aynı olan cümle, sözcük ve sayılara denilmektedir.
    
    const isPalindrom = str => str === str.split('').reverse().join('');
    
    // Örnekler
    isPalindrom('abc');         // false
    isPalindrom('abcba');       // true
    isPalindrom('123454321');   // true
  • Anagram olup olmadığını kontrol edin
    // Anagram, bir sözcüğün veya sözcük grubunun harflerinin değişik düzenle başka bir sözcüğü veya sözcük grubunu oluşturmasıdır
    const isAnagram = (str1, str2) => str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join('');
    
    // Örnekler
    isAnagram('özge', 'göze');          // true
    isAnagram('bahri', 'ihbar');        // true
    isAnagram('düzgün', 'gündüz');      // true
    isAnagram('algoritma', 'logaritma');    // true
  • Harfi emojiye çevirmek
    const charToEmoji = c => String.fromCodePoint(c.toLowerCase().charCodeAt() + 127365);
    
    // Örnekler
    charToEmoji('a');     // 🇦
    charToEmoji('b');     // 🇧
  • CamelCase formatına çevirme
    const toCamelCase = str => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
    
    // Örnekler
    toCamelCase('background-color');            // backgroundColor
    toCamelCase('-webkit-scrollbar-thumb');     // WebkitScrollbarThumb
    toCamelCase('_hello_world');                // HelloWorld
    toCamelCase('hello_world');                 // helloWorld
  • PascalCase formatına çevirme
    const toPascalCase = str => (str.match(/[a-zA-Z0-9]+/g) || []).map(w => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join('');
    
    // Örnekler
    toPascalCase('hello world');    // 'HelloWorld'
    toPascalCase('hello.world');    // 'HelloWorld'
    toPascalCase('foo_bar-baz');    // FooBarBaz
  • URL de gösterilecek formata çevirme
    const slugify = string => string.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');
    
    // Örnek
    slugify('Chapter One: Once upon a time...');    // 'chapter-one-once-upon-a-time'
  • Unix dosya yoluna çevirme
    const toUnixPath = path => path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, '');
    
    // Örnekler
    toUnixPath('./foo/bar/baz');        // foo/bar/baz
    toUnixPath('C:\\foo\\bar\\baz');    // /foo/bar/baz
  • Kebap formatından Camel formatına çevirme , ya da tam tersi
    const kebabToCamel = str => str.replace(/-./g, m => m.toUpperCase()[1]);
    
    const camelToKebab = str => str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
    
    // Örnekler
    kebabToCamel('background-color');   // 'backgroundColor'
    camelToKebab('backgroundColor');    // 'background-color'
  • Snake formatını Camel formatına çevirme
    const snakeToCamel = str => str.toLowerCase().replace(/(_\w)/g, m => m.toUpperCase().substr(1));
    
    // Örnek
    snakeToCamel('HELLO_world');    // 'helloWorld'
  • Harfin exceldeki sıra numarasını bulma
    const excelIndex = col => col.split('').reduce((prev, next) => prev * 26 + parseInt(next, 36) - 9, 0);
    
    // Örnekler
    excelIndex('A');      // 1
    excelIndex('B');      // 2
    excelIndex('C');      // 3
    excelIndex('Z');      // 26
    
    excelIndex('AA');     // 27
    excelIndex('AB');     // 28
    excelIndex('AC');     // 29
    excelIndex('AZ');     // 52
    
    excelIndex('AAA');    // 703
    excelIndex('AAB');    // 704
  • HTML karakterleri yazılabilir formata çevirme
    const escape = str => str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;');
    
    // Ya da
    const escape = str => str.replace(/[&<>"']/g, m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[m]);
  • HTML özel karakter oluşturma
    const unescape = str => str.replace(/&amp;/g , '&').replace(/&lt;/g  , '<').replace(/&gt;/g  , '>').replace(/&#0*39;/g , "'").replace(/&quot;/g, '"');
  • Temel url'yi herhangi bir parametre olmadan almak
    const baseUrl = url => url.indexOf('?') === -1 ? url : url.slice(0, url.indexOf('?'));
    
    // Ya da
    // Not: `includes` IE 11 ve öncesi desteklemiyor
    const baseUrl = url => url.includes('?') ? url.slice(0, url.indexOf('?')) : url;
    
    
    // Örnek
    baseUrl('https://hamza.com/hakkimda?foo=bar&hello=world');    // 'https://hamza.com/hakkimda'
  • Dosya uzantısını almak
    const uzanti = dosyaAdi => dosyaAdi.split('.').pop();
  • Linkten dosya ismini almak
    const dosyaAdi = url => url.substring(url.lastIndexOf('/') + 1);
    
    // Örnek
    dosyaAdi('http://hamza.com/path/to/document.pdf');     // 'document.pdf'
  • Yazının kaç byte yer kapladığını hesaplama
    const bytes = str => new Blob([str]).size;
    
    // Örnekler
    bytes('hello world');       // 11
    bytes('🎉');                // 4
  • İstenilen karakterin kaç adet olduğunu bulma
    const karakterSay = (string, karakter) => string.split(karakter).length - 1;
    
    // Ya da
    const karakterSay = (string, karakter) => string.replace((new RegExp(String.raw`[^${karakter}]`, 'g')), '').length;
    
    // Örnekler
    karakterSay('192.168.1.1', '.');     // 3
    karakterSay('hamza kaya', 'a');      // 4
  • Sadece ilk karakteri küçük harfle yazdırma
    const ilkHarfiKucult = str => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;
    
    // Örnek
    ilkHarfiKucult('Hello World');      // 'hello World'
  • Tüm boşlukları silme
    const bosluklariSil = str => str.replace(/\s/g, '');
    
    // Örnek
    bosluklariSil('hel lo wor ld');      // 'helloworld'
  • Yazıyı istenilen adet kadar tekrar yazdırma
    const tekrarla = (str, adet) => str.repeat(adet);
    
    // Ya da
    const tekrarla = (str, adet) => Array(adet).join(str);
  • Satır sonlarını html tagına çevirme (\n to br)
    const nl2br = str => str.replace(new RegExp('\r?\n', 'g'), '<br>');
    
    // React içinde
    str.split('\n').map((item, index) => <React.Fragment key={index}>{item}<br /></React.Fragment>)
  • Birden çok boşluğu tek bir boşlukla değiştirme
    // özel karakterler dahil hepsini temizleme
    const bosluklariTemizle = str => str.replace(/\s\s+/g, ' ');
    
    // sadece boşlukları temizlemek için
    const bosluklariTemizle = str => str.replace(/  +/g, ' ');
    
    
    // Örnek
    bosluklariTemizle('front\n   end     \t    \rdeveloper');  // 'front end developer'
  • Yazının istenilen karakter sayısını başka bir karakterle maskeleme
    const maskele = (str, length, mask) => `${str}`.slice(length).padStart(`${str}`.length, mask);
    
    // Örnek - ilk 6 karakteri * ile maskele
    maskele("1234567890", 6, '*');       // ******7890
  • Yazıyı tersten yazdırmak
    const tersten = str => str.split('').reverse().join('');
    
    // Ya da
    const tersten = str => [...str].reverse().join('');
    
    // Ya da
    const tersten = str => str.split('').reduce((rev, char)=> `${char}${rev}`, '');
    
    // Ya da
    const tersten = str => (str === '') ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`;
    
    // Örnek
    tersten('hello world');     // 'dlrow olleh'
  • Yazının harflerini alfabetik sıralama
    const sirala = str => str.split('').sort((a, b) => a.localeCompare(b)).join('');
    
    // Örnek
    sirala('javascript');    // aacijprstv
  • Ansi karakterleri temizlemek
    const clearAnsi = str => str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
    
    // Örnek
    clearAnsi('\u001B[4mcake\u001B[0m');                                                               // 'cake'
    clearAnsi('\u001B[0m\u001B[4m\u001B[42m\u001B[31mfoo\u001B[39m\u001B[49m\u001B[24mfoo\u001B[0m');  // 'foofoo'
  • Sadece baştaki ve sondaki slash karakterlerini silme
    const slashTemizle = str => str.replace(/^\/+|\/+$/g, '');
    
    // Ya da
    const slashTemizle = str => str.split('/').filter(Boolean).join('/');
    
    // Örnek
    slashTemizle('//hello/world///');    // hello/world
  • Yazının içinden istenilen karakteri temizleme
    const trim = (str, char) => str.split(char).filter(Boolean).join();
    
    // Örnekler
    trim('/hamza kaya//', '/');        // hamza kaya
  • Dosya uzantısını silme
    const uzantiSil = dosyaAdi => dosyaAdi.indexOf('.') === -1 ? dosyaAdi : dosyaAdi.split('.').slice(0, -1).join('.');
    
    // Örnekler
    uzantiSil('document');            // document
    uzantiSil('document.pdf');        // document
    uzantiSil('document.2020.pdf');   // document.2020
  • Yazının istenilen karakterden sonrasını maskeleme
    const maskele = (str, max, mask) => str.length < max ? str : `${str.substr(0, str.substr(0, max - mask.length).lastIndexOf(' '))}${mask}`;
    
    // Örnek
    maskele("Lorem Ipsum is simply", 15, '...');     // Lorem Ipsum...
  • Yazının içindeki tüm kelimelerin ilk harfini büyütmek
    const ilkHarfleriBuyut = str => str.split(' ').map(w => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join(' ');
    
    // Ya da
    const ilkHarfleriBuyut = str => str.replace(/^(.)|\s+(.)/g, c => c.toUpperCase());
    
    // Örnek
    ilkHarfleriBuyut('hamza kaya');      // 'Hamza KAYA'
Tarih
  • İki tarih arasındaki gün sayısı
    const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
    
    // Örnek
    diffDays(new Date('2014-12-19'), new Date('2020-01-01'));   // 1839
  • İki tarih arasındaki ay sayısı
    const monthDiff = (startDate, endDate) => Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
    
    // Örnek
    monthDiff(new Date('2020-01-01'), new Date('2021-01-01'));  // 12
    
    
  • İki tarihi karşılaştırma
    // `a` ve `b` birer `Date` objesi
    const karsilastir = (a, b) => a.getTime() === b.getTime();
    
    // Örnek
    karsilastir(new Date('2020-03-30'), new Date('2020-01-01'));    // false
  • Tarihi yıl-ay-gün şekline çevirme
    // `date` bir `Date` objesi
    const formatYmd = date => date.toISOString().slice(0, 10);
    
    // Örnek
    formatYmd(new Date());      // 2020-05-06
    
    
  • Saniyeyi saat formatına çevirme
    // `s` saniye 
    const formatSaniye = s => new Date(s * 1000).toISOString().substr(11, 8);
    
    // Ya da
    const formatSaniye = s => (new Date(s * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
    
    // Ya da
    const formatSaniye = s => [parseInt(s / 60 / 60), parseInt(s / 60 % 60), parseInt(s % 60)].join(':').replace(/\b(\d)\b/g, '0$1');
    
    // Örnekler
    formatSaniye(200);     // 00:03:20
    formatSaniye(500);     // 00:08:20
  • Tarih objesinden dizi oluşturma
    // `date` bir `Date` objesi
    const tarihDizisi = date => date.toISOString().split(/[^0-9]/).slice(0, -1);
    
    //  [yıl, ay, gün, saat, dakika, saniye, milisaniye] şeklinde değer dönecektir
  • Tarihi istenilen ülke formatına çevirme
    // `date` bir `Date` objesi
    // `locale` ülke dil kodu (en-US, tr-TR, gibi)
    const format = (date, locale) => new Intl.DateTimeFormat(locale).format(date);
    
    // Örnek
    format(new Date(), 'tr-TR');    // 30.08.2020
  • Saniye formatında şu an
    const ts = () => Math.floor(new Date().getTime() / 1000);
  • Tarihin yılın kaçıncı gününe denk geldiğini bulma
    // `date` bir Date objesi
    const yilinKacinciGunu = date => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));
    
    // Örnek
    yilinKacinciGunu(new Date(2020, 08, 30));      // 274
  • İstenilen tarihin ay ismini alma
    // `date` bir Date objesi
    const ayAdi = date => ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim','Kasım', 'Aralık'][date.getMonth()];
  • İstenilen ay/yıl kaç gün sürdüğünü öğrenme
    // `month` is zero-based index
    const gunSayisi = (ay, yil) => new Date(yil, ay, 0).getDate();
  • Yarının tarihi getirme
    const yarin = (d => new Date(d.setDate(d.getDate() + 1)))(new Date);
    
    // Ya da
    const yarin = new Date((new Date()).valueOf() + 1000 * 60 * 60 * 24);
  • Verilen tarihten günün ismini öğrenme
    // `date` bir Date objesi
    const gunIsmi = date => ['Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumastesi'][date.getDay()];
  • Dünün tarihi öğrenme
    const dun = (d => new Date(d.setDate(d.getDate() - 1)))(new Date);
    
    // Ya da
    const dun = new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24);
  • Artan/Azalan Tarih sıralaması
    // `arr` dizi ve içinde `Date` objeleri var
    const azalanTarih = arr => arr.sort((a, b) => a.getTime() > b.getTime());
    const artanTarih = arr => arr.sort((a, b) => a.getTime() < b.getTime());
Validator
  • Bir tarihin iki tarih arasında olup olmadığını kontrol etme
    // `min`, `max` ve `date` birer `Date` nesnesi
    const isBetween = (date, min, max) => (date.getTime() >= min.getTime() && date.getTime() <= max.getTime());
  • Tarihin bugüne ait olup olmadığını kontrol etme
    // `date` bir Date nesnesi
    const isToday = (date) => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10);
  • Asal sayı olup olmadığını kontrol etme
    const asalMi = num => (num > 1) && Array(Math.floor(Math.sqrt(num)) - 1).fill(0).map((_, i) => i + 2).every(i => num % i !== 0);
  • Bir sayının 2'nin üssü olup olmadığını kontrol etme
    const ikiUzeriMi = num => (number & (number - 1)) === 0;
    
    // Örnekler
    ikiUzeriMi(256);      // true
    ikiUzeriMi(129);      // false
  • Bir sayının tek sayı olup olmadığını kontrol etme
    const tekMi = number => number % 2 !== 0;
    
    // Ya da
    const tekMi = number => !!(number & 1);
    
    // Ya da
    const tekMi = number => !Number.isInteger(number / 2);
    
    // Örnekler
    tekMi(1);   // true
    tekMi(2);   // false
    
    
  • Bir sayının çift olup olmadığını kontrol etme
    const ciftMi = number => number % 2 === 0;
    
    // Ya da
    const ciftMi = number => number & 1 !== 0;
    
    // Ya da
    const ciftMi = number => !(number & 1);
    
    // Ya da
    const ciftMi = number => Number.isInteger(number / 2);
    
    // Örnekler
    ciftMi(1);      // false
    ciftMi(2);      // true
    
    
  • Bir sayının belirli bir aralıkta olup olmadığını kontrol etme
    const araliktaMi = (num, a, b) => (Math.min(a, b) <= num && num < Math.max(a, b));
    
    // Örnek
    araliktaMi(10, 5, 15);         // true
    araliktaMi(10, 5, 6);          // false
    araliktaMi(10, 15, 5);         // true
    araliktaMi(-10, -5, -15);      // true
  • Bir sayının negatif olup olmadığını kontrol etme
    const negatifMi = number => Math.sign(number) === -1;
    
    // Ya da
    const negatifMi = number => number < 0;
    
    // Örnekler
    negatifMi(-3);     // true
    negatifMi(8);      // false
    
    
  • Bir sayının pozitif olup olmadığını kontrol etme
    const pozitifMi = number => Math.sign(number) === 1;
    
    // Örnekler
    pozitifMi(3);      // true
    pozitifMi(-8);     // false
  • Yazının içinde küçük harf içerip içermediğini kontrol etme
    const kucukHarfVarmi = str => str !== str.toUpperCase();
    
    // Örnekler
    kucukHarfVarmi('Hello World');   // true
    kucukHarfVarmi('HELLO WORLD');   // false
  • Bir yazının sadece ascii karakterlerden oluştuğunu kontrol etme
    const ascii = str => /^[\x00-\x7F]+$/.test(str);
  • Bir dizenin yalnızca rakam içerip içermediğini kontrol etme
    const isNumeric = str => !/[^0-9]/.test(str);
    
    // Örnekler
    isNumeric(2);               // true
    isNumeric('23');            // true
    isNumeric('00123');         // true
    
    isNumeric('1.23');          // false
    isNumeric('-Infinity');     // false
    isNumeric('Infinity');      // false
    isNumeric('NaN');           // false
  • Bir dizenin yalnızca harf ve rakam içerip içermediğini kontrol etme
    const isAlphanumeric = str => /^[0-9A-Z]+$/i.test(str);
    
    // Örnekler
    isAlphanumeric('helloworld');           // true
    isAlphanumeric('HelloWorld');           // true
    isAlphanumeric('hello world');          // false
    isAlphanumeric('hello123');             // true
    isAlphanumeric('hello 123');            // false
  • Sadece karaktermi kontrolü
    const isAlpha = str => /^[A-Z]+$/i.test(str);
    
    // Örnekler
    isAlpha('helloworld');          // true
    isAlpha('HelloWorld');          // true
    isAlpha('hello world');         // false
    isAlpha('0123456789');          // false
  • İlk karakter büyük harf'mi kontrolü
    const isFirstUpperCase = str => str !== str.toLowerCase();
    
    // Örnekler
    isFirstUpperCase('Hello World');   // true
    isFirstUpperCase('hello world');   // false
  • Boşluk karakteri var mı kontrol etme
    const containsWhitespace = str => str => /\s/.test(str);
    
    // Örnek
    containsWhitespace('hello world');      // true
  • Doğru bir hex renk kodu mu kontrol etme
    const isHexColor = color => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color);
    
    // Örnekler
    isHexColor('#012');         // true
    isHexColor('#A1B2C3');      // true
    isHexColor('012');          // false
    isHexColor('#GHIJKL');      // false
  • Ondalık sayı olup olmadığını kontrol etme
    const isHexadecimal = str => /^[A-F0-9]+$/i.test(str);
    
    // Ya da
    const isHexadecimal = str => str.split('').every(c => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);
    
    // Örnekler
    isHexadecimal('123');       // true
    isHexadecimal('A1B2C3');    // true
    isHexadecimal('#123');      // false
  • Yazının tamamının küçük harf olup olmadığını kontrol etme
    const isLowerCase = str => str === str.toLowerCase();
  • Yazının tamamının büyük harf olup olmadığını kontrol etme
    const isUpperCase = str => str === str.toUpperCase();
  • Gerçek bir sayı olup olmadığını kontrol etme
    const isNumber = value => !isNaN(parseFloat(value)) && isFinite(value);
  • Obje olup olmadığını kontrol etme
    
    const isObject = (obj) => obj instanceof Object && !Array.isArray(obj)
    
    // Obje olduğu halde class nesnesi vs. durumlar için
    const isObject = obj => (!!obj && typeof obj === 'object' && (obj.__proto__ === null || obj.__proto__ === Object.prototype));
    
    
    // Örnekler
    isPlainObject(null);                    // false
    isPlainObject('hello world');           // false
    isPlainObject([]);                      // false
    isPlainObject(Object.create(null));     // false
    isPlainObject(function() {});           // false
    
    isPlainObject({});                      // true
    isPlainObject({ a: '1', b: '2' });      // true
  • Regex olup olmadığını kontrol etme
    const isRegExp = value => Object.prototype.toString.call(value) === '[object RegExp]';
  • String olup olmadığını kontrol etme
    const isString = value => Object.prototype.toString.call(value) === '[object String]';
    
    // Örnekler
    isString('hello world');                // true
    isString(new String('hello world'));    // true
    isString(10);                           // false
  • Nil kontorlü (null \ undefined)
    const isNil = (value) => value == null;
  • Artık yıl kontrolü (şubat 29 mu)
    const isLeapYear = year => (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
    
    // Ya da
    // Get the number of days in February
    const isLeapYear = year => new Date(year, 1, 29).getDate() === 29;
  • Dizideki tüm değerler aynı ve istenilen değer mi
    const isEqual = (arr, value) => arr.every(item => item === value);
    
    // Ya da
    const isEqual = (arr, value) => !arr.some(item => item !== value);
    
    // Örnekler
    isEqual(['foo', 'foo'], 'foo');     // true
    isEqual(['foo', 'bar'], 'foo');     // false
    isEqual(['bar', 'bar'], 'foo');     // false
  • Dizideki tüm değerler aynı mı
    const areEqual = arr => arr.length > 0 && arr.every(item => item === arr[0]);
    
    // Ya da
    const areEqual = arr => new Set(arr).size === 1;
    
    // Örnekler
    areEqual([1, 2, 3, 4]);                 // false
    areEqual(['hello', 'hello', 'hello']);  // true
  • Dizideki tüm değerler istenilen yapıda mı kontrol etme
    const contains = (arr, func) => arr.some(v => func(v));
    
    // Örnekler
    contains([10, 20, 30], v => v > 25 );               // true
    contains([10, 20, 30], v => v > 100 || v < 15 );    // true
    contains([10, 20, 30], v => v > 100 );              // false
  • Dizide gerçekten bir eleman var mı kontrol etme
    const isNotEmpty = arr => Array.isArray(arr) && Object.keys(arr).length > 0;
    
    // Örnekler
    isNotEmpty([]);             // false
    isNotEmpty([1, 2, 3]);      // true
  • Dizideki tüm değerler diğer dizide geçiyor mu kontrol etme
    const isSubset = (subArray, mainArray) => (new Set(mainArray)).size === (new Set(mainArray.concat(subArray))).size;
    
    // Ya da
    const isSubset = (subArray, mainArray) => mainArray.join("|").includes(subArray.join("|"));
    
    
    // Örnekler
    isSubset([1, 2], [1, 2, 3, 4]);     // true
    isSubset([1, 2, 5], [1, 2, 3, 4]);  // false
    isSubset([6], [1, 2, 3, 4]);        // false
  • Promise değer olup olmadığını kontrol etme
    const isPromise = obj => !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
  • ay/gün/yıl gerçekten var mı kontrol etme
    // `m`: ay (sıfırdan başlıyor)
    // `d`: gün
    // `y`: yıl
    const isValidDate = (m, d, y) => 0 <= m && m <= 11 && 0 < y && y < 32768 && 0 < d && d <= (new Date(y, m, 0)).getDate();
Çeşitli_Fonksiyonlar
  • Çalışma ortamı kontrolü (Node)
    const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
  • Çalışma ortamı kontrolü (Tarayıcı)
    const isBrowser = typeof window === 'object' && typeof document === 'object';
  • Celsius - Fahrenheit dönüştürme
    const celsiusToFahrenheit = celsius => celsius * 9/5 + 32;
    
    const fahrenheitToCelsius = fahrenheit => (fahrenheit - 32) * 5/9;
    
    // Örnekler
    celsiusToFahrenheit(15);    // 59
    celsiusToFahrenheit(0);     // 32
    celsiusToFahrenheit(-20);   // -4
    
    // ya da
    fahrenheitToCelsius(59);    // 15
    fahrenheitToCelsius(32);    // 0
  • Cookieleri obje olarak getirme
    const cookies = document.cookie.split(';').map(item => item.split('=')).reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});
  • Hex değerini RGB ye çevirme
    const hexToRgb = hex => hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`).substring(1).match(/.{2}/g).map(x => parseInt(x, 16));
    
    // Örnekler
    hexToRgb('#00ffff');    // [0, 255, 255] 
    hexToRgb('#0ff');       // [0, 255, 255]
  • RGB değerini Hex e çevirme
    const rgbToHex = (red, green, blue) => `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`;
    
    // Ya da
    const rgbToHex = (red, green, blue) => `#${[red, green, blue].map(v => v.toString(16).padStart(2, '0')).join('')}`;
    
    // Örnek
    rgbToHex(0, 255, 255);      // '#00ffff' 
  • JWT decode etme
    const decode = token => JSON.parse(decodeURIComponent(atob(token.split('.')[1].replace('-', '+').replace('_', '/')).split('').map(c => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`).join('')));
    
    
    // Örnek
    decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkhhbXphIEtBWUEiLCJhZG1pbiI6dHJ1ZSwiZXhwIjoxNTk5NzUwMjg2LCJqdGkiOiIzMTRjNGQ3My0yM2Y2LTRiYTgtOTBiZS0yZTA2YWI2ZWNlNWYiLCJpYXQiOjE1OTk3NDY2ODZ9.xbynCXVnNpor0JBHHBjCRtWi-SLKEgKOdV_sTep4kYM');
    
    /*
    {
      "sub": "1234567890",
      "name": "Hamza KAYA",
      "admin": true,
      "exp": 1599750286,
      "jti": "314c4d73-23f6-4ba8-90be-2e06ab6ece5f",
      "iat": 1599746686
    }
    */
    
  • Tarayıcının dark modunu kontrol etme
    const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
  • Hareket Hızı (Easing) fonksiyonları
    // Örnek easing fonksiyonları
    // Kaynak https://gist.github.com/gre/1650294 ve https://easings.net
    
    const linear = t => t;
    
    const easeInQuad = t => t * t;
    const easeOutQuad = t => t * (2-t);
    const easeInOutQuad = t => t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    
    const easeInCubic = t => t * t * t;
    const easeOutCubic = t => (--t) * t * t + 1;
    const easeInOutCubic = t => t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
    
    const easeInQuart = t => t * t * t * t;
    const easeOutQuart = t => 1 - (--t) * t * t * t;
    const easeInOutQuart = t => t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t;
    
    const easeInQuint = t => t * t * t * t * t;
    const easeOutQuint = t => 1 + (--t) * t * t * t * t;
    const easeInOutQuint = t => t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t;
    
    const easeInSine = t => 1 + Math.sin(Math.PI / 2 * t - Math.PI / 2);
    const easeOutSine = t => Math.sin(Math.PI / 2 * t);
    const easeInOutSine = t => (1 + Math.sin(Math.PI * t - Math.PI / 2)) / 2;
    
    const easeInElastic = t => (.04 - .04 / t) * Math.sin(25 * t) + 1;
    const easeOutElastic = t => .04 * t / (--t) * Math.sin(25 * t);
    const easeInOutElastic = t => (t -= .5) < 0 ? (.02 + .01 / t) * Math.sin(50 * t) : (.02 - .01 / t) * Math.sin(50 * t) + 1;
  • Zar atma değeri
    const zarAt = () => ~~(Math.random() * 6) + 1;
    
    // Örnekler
    zarAt();    // 4 
    zarAt();    // 1 
    zarAt();    // 6 
  • URL Encode etmek
    // `encodeURIComponent` özel karakterleri encode edemez  -_.!~*'()
    const encodeURL = url => encodeURIComponent(url).replace(/!/g, '%21').replace(/~/g, '%7E').replace(/\*/g, '%2A').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%20/g, '+');
  • İlk düzgün değeri getirme
    const firstValue = (...args) => args.find(item => item !== undefined && item !== null);
    
    // Ya da
    const firstValue = (...args) => args.find(item => ![undefined, null].includes(item));
    
    // Örnekler
    firstValue(undefined, null, 'deneme', NaN);     // 'deneme'
  • Tarayıcıdan istenen cookie değerini çekme
    const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
    
    // Örnek
    cookie('_ga');      // GA1.2.825309271.1581874719
  • İstenilen url den queryString parametresini alma
    const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param);
    
    const getParams = url => Object.fromEntries(new URLSearchParams(new URL(url).search).entries());
    
    
    // Örnek
    getParam('http://test.com?message=hello', 'message');     // 'hello'
    
    // Tüm değerleri almak için
    getParams('http://test.com?message=hello&query=text&page=5')
    // {"message":"hello","query":"text","page":"5"}
    
    
  • Http sayfayı https'ye yönlendirme
    const redirectHttps = () => (location.protocol === 'https:') ? {} : location.replace(`https://${location.href.split('//')[1]}`);
    
    // Ya da
    const redirectHttps = () => (location.protocol === 'https:') ? {} : (location.protocol = 'https:');
  • Promise değişkeni ile çalıştırma
    // `promises` dizi ve `Promise` objesi
    const run = promises => promises.reduce((p, c) => p.then(rp => c.then(rc => [...rp, rc])), Promise.resolve([]));
    
    // Örnek
    run(promises).then((results) => {
        // `results` dizi olarak dönecektir
    });
  • İki değişkenin değerlerini bir biri ile değiştirme
    [a, b] = [b, a];
  • Bekleme yaptırma
    const bekle = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));