ES6[edit]
//-------------------------------------------[ Dancing Links and Algorithm X ]--
/**
 * The doubly-doubly circularly linked data object.
 * Data object X
 */
class DoX {
  /**
   * @param {string} V
   * @param {!DoX=} H
   */
  constructor(V, H) {
    this.V = V;
    this.L = this;
    this.R = this;
    this.U = this;
    this.D = this;
    this.S = 1;
    this.H = H || this;
    H && (H.S += 1);
  }
}

/**
 * Helper function to help build a horizontal doubly linked list.
 * @param {!DoX} e An existing node in the list.
 * @param {!DoX} n A new node to add to the right of the existing node.
 * @return {!DoX}
 */
const addRight = (e, n) => {
  n.R = e.R;
  n.L = e;
  e.R.L = n;
  return e.R = n;
};

/**
 * Helper function to help build a vertical doubly linked list.
 * @param {!DoX} e An existing node in the list.
 * @param {!DoX} n A new node to add below the existing node.
 */
const addBelow = (e, n) => {
  n.D = e.D;
  n.U = e;
  e.D.U = n;
  return e.D = n;
};

/**
 * Verbatim copy of DK's search algorithm. The meat of the DLX algorithm.
 * @param {!DoX} h The root node.
 * @param {!Array<!DoX>} s The solution array.
 */
const search = function(h, s) {
  if (h.R == h) {
    printSol(s);
  } else {
    let c = chooseColumn(h);
    cover(c);
    for (let r = c.D; r != c; r = r.D) {
      s.push(r);
      for (let j = r.R; r !=j; j = j.R) {
        cover(j.H);
      }
      search(h, s);
      r = s.pop();
      for (let j = r.R; j != r; j = j.R) {
        uncover(j.H);
      }
    }
    uncover(c);
  }
};

/**
 * Verbatim copy of DK's algorithm for choosing the next column object.
 * @param {!DoX} h
 * @return {!DoX}
 */
const chooseColumn = h => {
  let s = Number.POSITIVE_INFINITY;
  let c = h;
  for(let j = h.R; j != h; j = j.R) {
    if (j.S < s) {
      c = j;
      s = j.S;
    }
  }
  return c;
};

/**
 * Verbatim copy of DK's cover algorithm
 * @param {!DoX} c
 */
const cover = c => {
  c.L.R = c.R;
  c.R.L = c.L;
  for (let i = c.D; i != c; i = i.D) {
    for (let j = i.R; j != i; j = j.R) {
      j.U.D = j.D;
      j.D.U = j.U;
      j.H.S = j.H.S - 1;
    }
  }
};

/**
 * Verbatim copy of DK's cover algorithm
 * @param {!DoX} c
 */
const uncover = c => {
  for (let i = c.U; i != c; i = i.U) {
    for (let j = i.L; i != j; j = j.L) {
      j.H.S = j.H.S + 1;
      j.U.D = j;
      j.D.U = j;
    }
  }
  c.L.R = c;
  c.R.L = c;
};

//-----------------------------------------------------------[ Print Helpers ]--
/**
 * Given the standard string format of a grid, print a formatted view of it.
 * @param {!string|!Array} a
 */
const printGrid = function(a) {

  const getChar = c => {
    let r = Number(c);
    if (isNaN(r)) { return c }

    let o = 48;
    if (r > 9 && r < 36) { o = 55 }
    if (r >= 36) { o = 61 }
    return String.fromCharCode(r + o)
  };

  a = 'string' == typeof a ? a.split('') : a;

  let U = Math.sqrt(a.length);
  let N = Math.sqrt(U);
  let line = new Array(N).fill('+').reduce((p, c) => {
    p.push(... Array.from(new Array(1 + N*2).fill('-')));
    p.push(c);
    return p;
  }, ['\n+']).join('') + '\n';

  a = a.reduce(function(p, c, i) {
      let d = i && !(i % U), G = i && !(i % N);
      i = !(i % (U * N));
      d && !i && (p += '|\n| ');
      d && i && (p += '|');
      i && (p = '' + p + line + '| ');
      return '' + p + (G && !d ? '| ' : '') + getChar(c) + ' ';
    }, '') + '|' + line;
  console.log(a);

};

/**
 * Given a search solution, print the resultant grid.
 * @param {!Array<!DoX>} a An array of data objects
 */
const printSol = a => {
  printGrid(a.reduce((p, c) => {
    let [i, v] = c.V.split(':');
    p[i * 1] = v;
    return p;
  }, new Array(a.length).fill('.')));
};

//----------------------------------------------[ Grid to Exact cover Matrix ]--
/**
 * Helper to get some meta about the grid.
 * @param {!string} s The standard string representation of a grid.
 * @return {!Array}
 */
const gridMeta = s => {
  const g = s.split('');
  const cellCount = g.length;
  const tokenCount = Math.sqrt(cellCount);
  const N = Math.sqrt(tokenCount);
  const g2D = g.map(e => isNaN(e * 1) ?
    new Array(tokenCount).fill(1).map((_, i) => i + 1) :
    [e * 1]);
  return [cellCount, N, tokenCount, g2D];
};

/**
 * Given a cell grid index, return the row, column and box indexes.
 * @param {!number} n The n-value of the grid. 3 for a 9x9 sudoku.
 * @return {!function(!number): !Array<!number>}
 */
const indexesN = n => i => {
    let c = Math.floor(i / (n * n));
    i %= n * n;
    return [c, i, Math.floor(c / n) * n + Math.floor(i / n)];
};

/**
 * Given a puzzle string, reduce it to an exact-cover matrix and use
 * Donald Knuth's DLX algorithm to solve it.
 * @param puzString
 */
const reduceGrid = puzString => {

  printGrid(puzString);
  const [
    numCells,   // The total number of cells in a grid (81 for a 9x9 grid)
    N,          // the 'n' value of the grid. (3 for a 9x9 grid)
    U,          // The total number of unique tokens to be placed.
    g2D         // A 2D array representation of the grid, with each element
                // being an array of candidates for a cell. Known cells are
                // single element arrays.
  ] = gridMeta(puzString);

  const getIndex = indexesN(N);

  /**
   * The DLX Header row.
   * Its length is 4 times the grid's size. This is to be able to encode
   * each of the 4 Sudoku constrains, onto each of the cells of the grid.
   * The array is initialised with unlinked DoX nodes, but in the next step
   * those nodes are all linked.
   * @type {!Array.<!DoX>}
   */
  const headRow = new Array(4 * numCells)
    .fill('')
    .map((_, i) => new DoX(`H${i}`));

  /**
   * The header row root object. This is circularly linked to be to the left
   * of the first header object in the header row array.
   * It is used as the entry point into the DLX algorithm.
   * @type {!DoX}
   */
  let H = new DoX('ROOT');
  headRow.reduce((p, c) => addRight(p, c), H);

  /**
   * Transposed the sudoku puzzle into a exact cover matrix, so it can be passed
   * to the DLX algorithm to solve.
   */
  for (let i = 0; i < numCells; i++) {
    const [ri, ci, bi] = getIndex(i);
    g2D[i].forEach(num => {
      let id = `${i}:${num}`;
      let candIdx = num - 1;

      // The 4 columns that we will populate.
      const A = headRow[i];
      const B = headRow[numCells + candIdx + (ri * U)];
      const C = headRow[(numCells * 2) + candIdx + (ci * U)];
      const D = headRow[(numCells * 3) + candIdx + (bi * U)];

      // The Row-Column Constraint
      let rcc = addBelow(A.U, new DoX(id, A));

      // The Row-Number Constraint
      let rnc = addBelow(B.U, addRight(rcc, new DoX(id, B)));

      // The Column-Number Constraint
      let cnc = addBelow(C.U, addRight(rnc, new DoX(id, C)));

      // The Block-Number Constraint
      addBelow(D.U, addRight(cnc, new DoX(id, D)));
    });
  }
  search(H, []);
};

[
  '819..5.....2...75..371.4.6.4..59.1..7..3.8..2..3.62..7.5.7.921..64...9.....2..438',
  '53..247....2...8..1..7.39.2..8.72.49.2.98..7.79.....8.....3.5.696..1.3...5.69..1.',
  '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..',
  '394..267....3..4..5..69..2..45...9..6.......7..7...58..1..67..8..9..8....264..735',
  '97.3...6..6.75.........8.5.......67.....3.....539..2..7...25.....2.1...8.4...73..',
  '4......6.5...8.9..3....1....2.7....1.9.....4.8....3.5....2....7..6.5...8.1......6',
  '85...24..72......9..4.........1.7..23.5...9...4...........8..7..17..........36.4.',
  '..1..5.7.92.6.......8...6...9..2.4.1.........3.4.8..9...7...3.......7.69.1.8..7..',
  '.9...4..7.....79..8........4.58.....3.......2.....97.6........4..35.....2..6...8.',
  '12.3....435....1....4........54..2..6...7.........8.9...31..5.......9.7.....6...8',
  '9..2..5...4..6..3...3.....6...9..2......5..8...7..4..37.....1...5..2..4...1..6..9',
  '1....7.9..3..2...8..96..5....53..9...1..8...26....4...3......1..4......7..7...3..',
  '12.4..3..3...1..5...6...1..7...9.....4.6.3.....3..2...5...8.7....7.....5.......98',
  '..............3.85..1.2.......5.7.....4...1...9.......5......73..2.1........4...9',
  '.......39.....1..5..3.5.8....8.9...6.7...2...1..4.......9.8..5..2....6..4..7.....',
  '....839..1......3...4....7..42.3....6.......4....7..1..2........8...92.....25...6',
  '..3......4...8..36..8...1...4..6..73...9..........2..5..4.7..686........7..6..5..'
].forEach(reduceGrid);

// Or of you want to create all the grids of a particular n-size.
// I run out of stack space at n = 9
let n = 2;
let s = new Array(Math.pow(n, 4)).fill('.').join('');
reduceGrid(s);

+-------+-------+-------+
| . . 3 | . . . | . . . |
| 4 . . | . 8 . | . 3 6 |
| . . 8 | . . . | 1 . . |
+-------+-------+-------+
| . 4 . | . 6 . | . 7 3 |
| . . . | 9 . . | . . . |
| . . . | . . 2 | . . 5 |
+-------+-------+-------+
| . . 4 | . 7 . | . 6 8 |
| 6 . . | . . . | . . . |
| 7 . . | 6 . . | 5 . . |
+-------+-------+-------+

+-------+-------+-------+
| 1 2 3 | 4 5 6 | 7 8 9 |
| 4 5 7 | 1 8 9 | 2 3 6 |
| 9 6 8 | 3 2 7 | 1 5 4 |
+-------+-------+-------+
| 2 4 9 | 5 6 1 | 8 7 3 |
| 5 7 6 | 9 3 8 | 4 1 2 |
| 8 3 1 | 7 4 2 | 6 9 5 |
+-------+-------+-------+
| 3 1 4 | 2 7 5 | 9 6 8 |
| 6 9 5 | 8 1 4 | 3 2 7 |
| 7 8 2 | 6 9 3 | 5 4 1 |
+-------+-------+-------+

"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format."


ES5[edit]
function knuthShuffle(arr) {
    var rand, temp, i;

    for (i = arr.length - 1; i > 0; i -= 1) {
        rand = Math.floor((i + 1) * Math.random());//get random between zero and i (inclusive)
        temp = arr[rand];
        arr[rand] = arr[i]; //swap i (last element) with random element.
        arr[i] = temp;
    }
    return arr;
}

var res = {
    '1,2,3': 0, '1,3,2': 0,
    '2,1,3': 0, '2,3,1': 0,
    '3,1,2': 0, '3,2,1': 0
};

for (var i = 0; i < 100000; i++) {
    res[knuthShuffle([1,2,3]).join(',')] += 1;
}

for (var key in res) {
    print(key + "\t" + res[key]);
}

1,2,3   16619
1,3,2   16614
2,1,3   16752
2,3,1   16959
3,1,2   16460
3,2,1   16596
ES6[edit]
Mutating in-place swap[edit]
(() => {

    // knuthShuffle :: [a] -> [a]
    const knuthShuffle = xs =>
        enumFromTo(0, xs.length - 1)
        .reduceRight((a, i) => {
            const
                iRand =  randomRInt(0, i),
                tmp = a[iRand];
            return iRand !== i ? (
                a[iRand] = a[i],
                a[i] = tmp,
                a
            ) : a;
        }, xs);

    const test = () => knuthShuffle(
        (`alpha beta gamma delta epsilon zeta
              eta theta iota kappa lambda mu`)
        .split(/\s+/)
    );

    // GENERIC FUNCTIONS ----------------------------------

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = (m, n) =>
        n >= m ? (
            iterateUntil(x => x >= n, x => 1 + x, m)
        ) : [];

    // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
    const iterateUntil = (p, f, x) => {
        let vs = [x],
            h = x;
        while (!p(h))(h = f(h), vs.push(h));
        return vs;
    };

    // randomRInt :: Int -> Int -> Int
    const randomRInt = (low, high) =>
        low + Math.floor(
            (Math.random() * ((high - low) + 1))
        );

    return test();
})();

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. It can be modified to return a new array if in-place modification is not suitable. The algorithm can also be adjusted to iterate from left to right if needed.


ES5[edit]
Iteration[edit]
Works with: Nodejs
var last_friday_of_month, print_last_fridays_of_month;

last_friday_of_month = function(year, month) {
  var i, last_day;
  i = 0;
  while (true) {
    last_day = new Date(year, month, i);
    if (last_day.getDay() === 5) {
      return last_day.toDateString();
    }
    i -= 1;
  }
};

print_last_fridays_of_month = function(year) {
  var month, results;
  results = [];
  for (month = 1; month <= 12; ++month) {
    results.push(console.log(last_friday_of_month(year, month)));
  }
  return results;
};

(function() {
  var year;
  year = parseInt(process.argv[2]);
  return print_last_fridays_of_month(year);
})();

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


"Display the string 'Goodbye, World!' in Node JS without a trailing newline."


Works with: FireFox or any JavaScript-enabled browser
var str = prompt("Enter a string");
var value = 0;
while (value != 75000) {
    value = parseInt( prompt("Enter the number 75000") );
}

"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface."


ES5[edit]
function caesar (text, shift) {
  return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) {
    return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26);
  });
}

// Tests
var text = 'veni, vidi, vici';
for (var i = 0; i<26; i++) {
  console.log(i+': '+caesar(text,i));
}

implement a Caesar cipher for encoding and decoding messages. The key used for the cipher is an integer between 1 and 25, which represents the number of positions each letter in the message is shifted in the alphabet. The cipher also supports both lower and upper case letters. The Caesar cipher is a simple mono-alphabetic substitution cipher and is identical to the Vigenère cipher with a key of length 1 and to the Rot-13 cipher with a key of 13.


ES5[edit]

function LCM(A)  // A is an integer array (e.g. [-50,25,-45,-18,90,447])
{
    var n = A.length, a = Math.abs(A[0]);
    for (var i = 1; i < n; i++)
     { var b = Math.abs(A[i]), c = a;
       while (a && b){ a > b ? a %= b : b %= a; }
       a = Math.abs(c*A[i])/(a+b);
     }
    return a;
}

/* For example:
   LCM([-50,25,-45,-18,90,447]) -> 67050
*/

ES6[edit]
Translation of: Haskell
(() => {
    'use strict';

    // gcd :: Integral a => a -> a -> a
    let gcd = (x, y) => {
        let _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b)),
            abs = Math.abs;
        return _gcd(abs(x), abs(y));
    }

    // lcm :: Integral a => a -> a -> a
    let lcm = (x, y) =>
        x === 0 || y === 0 ? 0 : Math.abs(Math.floor(x / gcd(x, y)) * y);

    // TEST
    return lcm(12, 18);

})();

calculate the least common multiple (LCM) of two integers. The LCM is the smallest positive integer that is a multiple of both given numbers. If either of the numbers is zero, the LCM is zero. The LCM can be calculated by iterating all multiples of one number until a multiple of the second number is found, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be computed for an array of integers using the associative law.


(() => {
    'use strict';

    // cusipValid = Dict Char Int -> String -> Bool
    const cusipValid = charMap => s => {
        const
            ns = fromMaybe([])(
                traverse(flip(lookupDict)(charMap))(
                    chars(s)
                )
            );
        return 9 === ns.length && (
            last(ns) === rem(
                10 - rem(
                    sum(apList(
                        apList([quot, rem])(
                            zipWith(identity)(
                                cycle([identity, x => 2 * x])
                            )(take(8)(ns))
                        )
                    )([10]))
                )(10)
            )(10)
        );
    };

    //----------------------- TEST ------------------------
    // main :: IO ()
    const main = () => {

        // cusipMap :: Dict Char Int
        const cusipMap = dictFromList(
            zip(chars(
                "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#"
            ))(enumFrom(0)));

        console.log(unlines(map(
            apFn(
                s => validity => s + ' -> ' + str(validity)
            )(cusipValid(cusipMap))
        )([
            '037833100',
            '17275R102',
            '38259P508',
            '594918104',
            '68389X106',
            '68389X105'
        ])));
    };

    //----------------- GENERIC FUNCTIONS -----------------

    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a =>
        b => ({
            type: 'Tuple',
            '0': a,
            '1': b,
            length: 2
        });

    // apFn :: (a -> b -> c) -> (a -> b) -> a -> c
    const apFn = f =>
        // Applicative instance for functions.
        // f(x) applied to g(x).
        g => x => f(x)(
            g(x)
        );

    // apList (<*>) :: [(a -> b)] -> [a] -> [b]
    const apList = fs =>
        // The sequential application of each of a list
        // of functions to each of a list of values.
        xs => fs.flatMap(
            f => xs.map(f)
        );

    // append (++) :: [a] -> [a] -> [a]
    // append (++) :: String -> String -> String
    const append = xs =>
        // A list or string composed by
        // the concatenation of two others.
        ys => xs.concat(ys);

    // chars :: String -> [Char]
    const chars = s =>
        s.split('');

    // cons :: a -> [a] -> [a]
    const cons = x =>
        xs => Array.isArray(xs) ? (
            [x].concat(xs)
        ) : 'GeneratorFunction' !== xs
        .constructor.constructor.name ? (
            x + xs
        ) : ( // cons(x)(Generator)
            function*() {
                yield x;
                let nxt = xs.next()
                while (!nxt.done) {
                    yield nxt.value;
                    nxt = xs.next();
                }
            }
        )();

    // cycle :: [a] -> Generator [a]
    function* cycle(xs) {
        const lng = xs.length;
        let i = 0;
        while (true) {
            yield(xs[i])
            i = (1 + i) % lng;
        }
    }

    // dictFromList :: [(k, v)] -> Dict
    const dictFromList = kvs =>
        Object.fromEntries(kvs);

    // enumFrom :: Enum a => a -> [a]
    function* enumFrom(x) {
        // A non-finite succession of enumerable
        // values, starting with the value x.
        let v = x;
        while (true) {
            yield v;
            v = succ(v);
        }
    }

    // flip :: (a -> b -> c) -> b -> a -> c
    const flip = f =>
        1 < f.length ? (
            (a, b) => f(b, a)
        ) : (x => y => f(y)(x));

    // fromEnum :: Enum a => a -> Int
    const fromEnum = x =>
        typeof x !== 'string' ? (
            x.constructor === Object ? (
                x.value
            ) : parseInt(Number(x))
        ) : x.codePointAt(0);

    // fromMaybe :: a -> Maybe a -> a
    const fromMaybe = def =>
        // A default value if mb is Nothing
        // or the contents of mb.
        mb => mb.Nothing ? def : mb.Just;

    // fst :: (a, b) -> a
    const fst = tpl =>
        // First member of a pair.
        tpl[0];

    // identity :: a -> a
    const identity = x =>
        // The identity function. (`id`, in Haskell)
        x;

    // last :: [a] -> a
    const last = xs =>
        // The last item of a list.
        0 < xs.length ? xs.slice(-1)[0] : undefined;

    // length :: [a] -> Int
    const length = xs =>
        // Returns Infinity over objects without finite
        // length. This enables zip and zipWith to choose
        // the shorter argument when one is non-finite,
        // like cycle, repeat etc
        (Array.isArray(xs) || 'string' === typeof xs) ? (
            xs.length
        ) : Infinity;

    // liftA2 :: (a -> b -> c) -> Maybe a -> Maybe b -> Maybe c
    const liftA2 = f => a => b =>
        a.Nothing ? a : b.Nothing ? b : Just(f(a.Just)(b.Just));

    // lookupDict :: a -> Dict -> Maybe b
    const lookupDict = k => dct => {
        const v = dct[k];
        return undefined !== v ? (
            Just(v)
        ) : Nothing();
    };

    // map :: (a -> b) -> [a] -> [b]
    const map = f =>
        // The list obtained by applying f
        // to each element of xs.
        // (The image of xs under f).
        xs => (
            Array.isArray(xs) ? (
                xs
            ) : xs.split('')
        ).map(f);

    // pureMay :: a -> Maybe a
    const pureMay = x => Just(x);

    // Given a type name string, returns a
    // specialised 'pure', where
    // 'pure' lifts a value into a particular functor.

    // pureT :: String -> f a -> (a -> f a)
    const pureT = t => x =>
        'List' !== t ? (
            'Either' === t ? (
                pureLR(x)
            ) : 'Maybe' === t ? (
                pureMay(x)
            ) : 'Node' === t ? (
                pureTree(x)
            ) : 'Tuple' === t ? (
                pureTuple(x)
            ) : pureList(x)
        ) : pureList(x);

    // pureTuple :: a -> (a, a)
    const pureTuple = x =>
        Tuple('')(x);

    // quot :: Int -> Int -> Int
    const quot = n =>
        m => Math.floor(n / m);

    // rem :: Int -> Int -> Int
    const rem = n => m => n % m;

    // snd :: (a, b) -> b
    const snd = tpl => tpl[1];

    // str :: a -> String
    const str = x =>
        x.toString();

    // succ :: Enum a => a -> a
    const succ = x => {
        const t = typeof x;
        return 'number' !== t ? (() => {
            const [i, mx] = [x, maxBound(x)].map(fromEnum);
            return i < mx ? (
                toEnum(x)(1 + i)
            ) : Error('succ :: enum out of range.')
        })() : x < Number.MAX_SAFE_INTEGER ? (
            1 + x
        ) : Error('succ :: Num out of range.')
    };

    // sum :: [Num] -> Num
    const sum = xs =>
        // The numeric sum of all values in xs.
        xs.reduce((a, x) => a + x, 0);

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n =>
        // The first n elements of a list,
        // string of characters, or stream.
        xs => 'GeneratorFunction' !== xs
        .constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

    // The first argument is a sample of the type
    // allowing the function to make the right mapping

    // toEnum :: a -> Int -> a
    const toEnum = e => x =>
        ({
            'number': Number,
            'string': String.fromCodePoint,
            'boolean': Boolean,
            'object': v => e.min + v
        } [typeof e])(x);

    // traverse :: (Applicative f) => (a -> f b) -> [a] -> f [b]
    const traverse = f =>
        // Collected results of mapping each element
        // of a structure to an action, and evaluating
        // these actions from left to right.
        xs => 0 < xs.length ? (() => {
            const
                vLast = f(xs.slice(-1)[0]),
                t = vLast.type || 'List';
            return xs.slice(0, -1).reduceRight(
                (ys, x) => liftA2(cons)(f(x))(ys),
                liftA2(cons)(vLast)(pureT(t)([]))
            );
        })() : [
            []
        ];

    // uncons :: [a] -> Maybe (a, [a])
    const uncons = xs => {
        // Just a tuple of the head of xs and its tail,
        // Or Nothing if xs is an empty list.
        const lng = length(xs);
        return (0 < lng) ? (
            Infinity > lng ? (
                Just(Tuple(xs[0])(xs.slice(1))) // Finite list
            ) : (() => {
                const nxt = take(1)(xs);
                return 0 < nxt.length ? (
                    Just(Tuple(nxt[0])(xs))
                ) : Nothing();
            })() // Lazy generator
        ) : Nothing();
    };

    // uncurry :: (a -> b -> c) -> ((a, b) -> c)
    const uncurry = f =>
        // A function over a pair, derived
        // from a curried function.
        x => ((...args) => {
            const
                xy = 1 < args.length ? (
                    args
                ) : args[0];
            return f(xy[0])(xy[1]);
        })(x);

    // unlines :: [String] -> String
    const unlines = xs =>
        // A single string formed by the intercalation
        // of a list of strings with the newline character.
        xs.join('\n');

    // zip :: [a] -> [b] -> [(a, b)]
    const zip = xs =>
        // Use of `take` and `length` here allows for zipping with non-finite
        // lists - i.e. generators like cycle, repeat, iterate.
        ys => {
            const
                lng = Math.min(length(xs), length(ys)),
                vs = take(lng)(ys);
            return take(lng)(xs).map(
                (x, i) => Tuple(x)(vs[i])
            );
        };

    // Use of `take` and `length` here allows zipping with non-finite lists
    // i.e. generators like cycle, repeat, iterate.

    // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    const zipWith = f => xs => ys => {
        const lng = Math.min(length(xs), length(ys));
        return Infinity > lng ? (() => {
            const
                as = take(lng)(xs),
                bs = take(lng)(ys);
            return Array.from({
                length: lng
            }, (_, i) => f(as[i])(
                bs[i]
            ));
        })() : zipWithGen(f)(xs)(ys);
    };

    // zipWithGen :: (a -> b -> c) ->
    // Gen [a] -> Gen [b] -> Gen [c]
    const zipWithGen = f => ga => gb => {
        function* go(ma, mb) {
            let
                a = ma,
                b = mb;
            while (!a.Nothing && !b.Nothing) {
                let
                    ta = a.Just,
                    tb = b.Just
                yield(f(fst(ta))(fst(tb)));
                a = uncons(snd(ta));
                b = uncons(snd(tb));
            }
        }
        return go(uncons(ga), uncons(gb));
    };

    // MAIN ---
    return main();
})();

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


"alpha beta gamma delta".split(" ").forEach(function (x) {
    console.log(x);
});

console.log("alpha beta gamma delta".split(" ").map(function (x) {
    return x.toUpperCase(x);
}).join("\n"));

console.log("alpha beta gamma delta".split(" ").reduce(function (a, x, i, lst) {
    return lst.length - i + ". " + x + "\n" + a;
}, ""));

for (var a in o) {
    print(o[a]);
}

for (var a in o) {
    if (o.hasOwnProperty(a)) {
        print(o[a]);
    }
}

Works with: JavaScript version 1.6
Deprecated

h = {"one":1, "two":2, "three":3}
for (x in h) print(x);
for each (y in h) print(y);

Works with: ECMAScript version 6th edition

h = {"one":1, "two":2, "three":3}
for (x in h) print(x);
for (y of h) print(y);

Iterates through each element in a collection in a specific order using a "for each" loop or an alternative loop if "for each" is not available. In ES5, it uses Array.forEach(), Array.map(), or Array.reduce() for arrays. It can also iterate over the keys of any object, including arrays, but may list inherited properties and methods. It can also iterate over the values of an object using a for each in or for of construct.


Works with: Firefox version 2.0
alert( "Hello,How,Are,You,Today".split(",").join(".") );

"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period."


function gcd(a,b) {
  a = Math.abs(a);
  b = Math.abs(b);

  if (b > a) {
    var temp = a;
    a = b;
    b = temp;
  }

  while (true) {
    a %= b;
    if (a === 0) { return b; }
    b %= a;
    if (b === 0) { return a; }
  }
}

function gcd_rec(a, b) {
  return b ? gcd_rec(b, a % b) : Math.abs(a);
}

function GCD(arr) {
  var i, y,
      n = arr.length,
      x = Math.abs(arr[0]);

  for (i = 1; i < n; i++) {
    y = Math.abs(arr[i]);

    while (x && y) {
      (x > y) ? x %= y : y %= x;
    }
    x += y;
  }
  return x;
}

//For example:
GCD([57,0,-45,-18,90,447]); //=> 3

find the greatest common divisor (GCD), also known as the greatest common factor (gcf) or greatest common measure, of two integers. The implementation is both iterative and recursive, and can work on an array of integers. Related tasks include finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.


Works with: Node.js
const net = require('net');

function handleClient(conn) {
    console.log('Connection from ' + conn.remoteAddress + ' on port ' + conn.remotePort);

    conn.setEncoding('utf-8');

    let buffer = '';

    function handleData(data) {
        for (let i = 0; i < data.length; i++) {
            const char = data.charAt(i);
            buffer += char;
            if (char === '\n') {
                conn.write(buffer);
                buffer = '';
            }
        }
    }

    conn.on('data', handleData);
}

net.createServer(handleClient).listen(12321, 'localhost');

Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.


function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
var value = "123.45e7"; // Assign string literal to value
if (isNumeric(value)) {
  // value is a number
}
//Or, in web browser in address field:
//  javascript:function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}; value="123.45e4"; if(isNumeric(value)) {alert('numeric')} else {alert('non-numeric')}

implement a boolean function that checks if a given string is a numeric string, including floating point and negative numbers, according to the language's syntax for numeric literals or numbers converted from strings.


Browser[edit]
fetch("https://sourceforge.net").then(function (response) {
    return response.text();
}).then(function (body) {
    return body;
});

Node.js[edit]
require("https").get("https://sourceforge.net", function (resp) {
    let body = "";
    resp.on("data", function (chunk) {
        body += chunk;
    });
    resp.on("end", function () {
        console.log(body);
    });
}).on("error", function (err) {
    console.error("Error: " + err.message);
});

Send a GET request to the URL "https://www.w3.org/", validate the host certificate, and print the obtained resource to the console without any authentication.


<html>
    <head>
	<script>
        function clip (subjectPolygon, clipPolygon) {

            var cp1, cp2, s, e;
            var inside = function (p) {
                return (cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]);
            };
            var intersection = function () {
                var dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ],
                    dp = [ s[0] - e[0], s[1] - e[1] ],
                    n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0],
                    n2 = s[0] * e[1] - s[1] * e[0],
                    n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]);
                return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3];
            };
            var outputList = subjectPolygon;
            cp1 = clipPolygon[clipPolygon.length-1];
            for (var j in clipPolygon) {
                cp2 = clipPolygon[j];
                var inputList = outputList;
                outputList = [];
                s = inputList[inputList.length - 1]; //last on the input list
                for (var i in inputList) {
                    e = inputList[i];
                    if (inside(e)) {
                        if (!inside(s)) {
                            outputList.push(intersection());
                        }
                        outputList.push(e);
                    }
                    else if (inside(s)) {
                        outputList.push(intersection());
                    }
                    s = e;
                }
                cp1 = cp2;
            }
            return outputList
        }

        function drawPolygon(context, polygon, strokeStyle, fillStyle) {
            context.strokeStyle = strokeStyle;
            context.fillStyle = fillStyle;
            context.beginPath();
            context.moveTo(polygon[0][0],polygon[0][1]); //first vertex
            for (var i = 1; i < polygon.length ; i++)
                context.lineTo(polygon[i][0],polygon[i][1]);
            context.lineTo(polygon[0][0],polygon[0][1]); //back to start
            context.fill();
            context.stroke();
            context.closePath();
        }

        window.onload = function () {
	        var context = document.getElementById('canvas').getContext('2d');
	        var subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]],
	            clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];
	        var clippedPolygon = clip(subjectPolygon, clipPolygon);
	        drawPolygon(context, clipPolygon, '#888','#88f');
	        drawPolygon(context, subjectPolygon, '#888','#8f8');
	        drawPolygon(context, clippedPolygon, '#000','#0ff');
    	}
        </script>
    <body>
    	<canvas id='canvas' width='400' height='400'></canvas>
    </body>
</html>

implement the Sutherland-Hodgman polygon clipping algorithm. It takes a closed polygon defined by given points and clips it by a rectangle defined by another set of points. The sequence of points that define the resulting clipped polygon is then printed. For extra credit, the code also displays all three polygons on a graphical surface, each in a different color, and fills the resulting polygon. The origin for display can be either north-west or south-west.


ES5[edit]

(function () {

    var xs = 'Solomon Jason Errol Garry Bernard Barry Stephen'.split(' '),
        ns = [44, 42, 42, 41, 41, 41, 39],

        sorted = xs.map(function (x, i) {
            return { name: x, score: ns[i] };
        }).sort(function (a, b) {
            var c = b.score - a.score;
            return c ? c : a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
        }),

        names = sorted.map(function (x) { return x.name; }),
        scores = sorted.map(function (x) { return x.score; }),

        reversed = scores.slice(0).reverse(),
        unique = scores.filter(function (x, i) {
            return scores.indexOf(x) === i;
        });

    // RANKINGS AS FUNCTIONS OF SCORES: SORTED, REVERSED AND UNIQUE

    var rankings = function (score, index) {
            return {
                name: names[index],
                score: score,

                Ordinal: index + 1,

                Standard: function (n) {
                    return scores.indexOf(n) + 1;
                }(score),

                Modified: function (n) {
                    return reversed.length - reversed.indexOf(n);
                }(score),

                Dense: function (n) {
                    return unique.indexOf(n) + 1;
                }(score),

                Fractional: function (n) {
                    return (
                        (scores.indexOf(n) + 1) +
                        (reversed.length - reversed.indexOf(n))
                    ) / 2;
                }(score)
            };
        },

        tbl = [
            'Name Score Standard Modified Dense Ordinal Fractional'.split(' ')
        ].concat(scores.map(rankings).reduce(function (a, x) {
            return a.concat([
                [x.name, x.score,
                    x.Standard, x.Modified, x.Dense, x.Ordinal, x.Fractional
                ]
            ]);
        }, [])),

        //[[a]] -> bool -> s -> s
        wikiTable = function (lstRows, blnHeaderRow, strStyle) {
            return '{| class="wikitable" ' + (
                strStyle ? 'style="' + strStyle + '"' : ''
            ) + lstRows.map(function (lstRow, iRow) {
                var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');

                return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) {
                    return typeof v === 'undefined' ? ' ' : v;
                }).join(' ' + strDelim + strDelim + ' ');
            }).join('') + '\n|}';
        };

    return wikiTable(tbl, true, 'text-align:center');

})();

The code implements five different ranking methods (Standard, Modified, Dense, Ordinal, and Fractional) for competitors in a competition based on their scores. The ranking methods handle ties differently: Standard shares the first ordinal number, Modified shares the last ordinal number, Dense shares the next available integer, Ordinal assigns the next available integer without treating ties, and Fractional shares the mean of their ordinal numbers. The code also sorts players with the same score alphabetically.


var
 radians = Math.PI / 4, // Pi / 4 is 45 degrees. All answers should be the same.
 degrees = 45.0,
 sine = Math.sin(radians),
 cosine = Math.cos(radians),
 tangent = Math.tan(radians),
 arcsin = Math.asin(sine),
 arccos = Math.acos(cosine),
 arctan = Math.atan(tangent);

// sine
window.alert(sine + " " + Math.sin(degrees * Math.PI / 180));
// cosine
window.alert(cosine + " " + Math.cos(degrees * Math.PI / 180));
// tangent
window.alert(tangent + " " + Math.tan(degrees * Math.PI / 180));
// arcsine
window.alert(arcsin + " " + (arcsin * 180 / Math.PI));
// arccosine
window.alert(arccos + " " + (arccos * 180 / Math.PI));
// arctangent
window.alert(arctan + " " + (arctan * 180 / Math.PI));

demonstrate the use of trigonometric functions such as sine, cosine, tangent, and their inverses in JavaScript. The functions accept arguments in radians, and conversion is performed when dealing with degrees. The same angle is used for non-inverse functions, while the same number is used for inverse functions, with results converted to both radians and degrees. If the language lacks certain functions, they are calculated using known approximations or identities.


<title></title>

Count

Item

unit weight

unit value

1

map

9

150

1

compass

13

35

1

water

153

200

2

glucose

15

60

3

banana

27

60

1

cheese

23

30

1

suntan, cream

11

70

1

waterproof, overclothes

43

75

1

note-case

22

80

1

sunglasses

7

20

1

socks

4

50

The code determines the optimal combination of items a tourist can carry in his knapsack, given a weight limit of 4 kg. It considers the weight, value, and quantity of each item, ensuring the total weight doesn't exceed the limit while maximizing the total value. The items cannot be divided. The output includes the total weight and value of the selected items.


(function(){
    var count=0
        secs=0

    var i= setInterval( function (){
        count++
        secs+=0.5
        console.log(count)
    }, 500);

    process.on('SIGINT', function() {
        clearInterval(i)
        console.log(secs+' seconds elapsed');
        process.exit()
    });
})();

an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program. This is implemented using the NodeJS engine.


ES6[edit]

let s = '9999';
let splusplus = (+s+1)+""

console.log([splusplus, typeof splusplus]) // 10000,string

Translation of: Python
Translation of: Haskell
(() => {
    'use strict';

    // succString :: Bool -> String -> String
    const succString = blnPruned => s => {
        const go = w => {
            const
                v = w.includes('.') ? (
                    parseFloat(w)
                ) : parseInt(w);
            return isNaN(v) ? (
                blnPruned ? [] : [w]
            ) : [(1 + v).toString()];
        };
        return unwords(concatMap(go, words(s)));
    };

    // TEST -----------------------------------------------
    const main = () =>
        console.log(
            unlines(
                ap(
                    map(succString, [true, false]),
                    ['41 pine martens in 1491.3 -1.5 mushrooms ≠ 136']
                )
            )
        );

    // GENERIC FUNCTIONS ----------------------------------

    // Each member of a list of functions applied to each
    // of a list of arguments, deriving a list of new values.

    // ap (<*>) :: [(a -> b)] -> [a] -> [b]
    const ap = (fs, xs) => //
        fs.reduce((a, f) => a.concat(
            xs.reduce((a, x) => a.concat([f(x)]), [])
        ), []);

    // concatMap :: (a -> [b]) -> [a] -> [b]
    const concatMap = (f, xs) =>
        xs.reduce((a, x) => a.concat(f(x)), []);

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) => xs.map(f);

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // unwords :: [String] -> String
    const unwords = xs => xs.join(' ');

    // words :: String -> [String]
    const words = s => s.split(/\s+/);

    // MAIN ---
    return main();
})();

"Increments a numerical string, expands the range of a stringSucc function to accommodate non-numeric noise and multiple numeric expressions in a single string using implicit coercion."


/**
 * Given an array of strings, return an array of arrays, containing the
 * strings split at the given separator
 * @param {!Array<!string>} a
 * @param {string} sep
 * @returns {!Array<!Array<string>>}
 */
const splitStrings = (a, sep = '/') => a.map(i => i.split(sep));

/**
 * Given an index number, return a function that takes an array and returns the
 * element at the given index
 * @param {number} i
 * @return {function(!Array<*>): *}
 */
const elAt = i => a => a[i];

/**
 * Transpose an array of arrays:
 * Example:
 * [['a', 'b', 'c'], ['A', 'B', 'C'], [1, 2, 3]] ->
 * [['a', 'A', 1], ['b', 'B', 2], ['c', 'C', 3]]
 * @param {!Array<!Array<*>>} a
 * @return {!Array<!Array<*>>}
 */
const rotate = a => a[0].map((e, i) => a.map(elAt(i)));

/**
 * Checks of all the elements in the array are the same.
 * @param {!Array<*>} arr
 * @return {boolean}
 */
const allElementsEqual = arr => arr.every(e => e === arr[0]);

const commonPath = (input, sep = '/') => rotate(splitStrings(input, sep))
    .filter(allElementsEqual).map(elAt(0)).join(sep);

const cdpInput = [
  '/home/user1/tmp/coverage/test',
  '/home/user1/tmp/covert/operator',
  '/home/user1/tmp/coven/members',
];

console.log(`Common path is: ${commonPath(cdpInput)}`);

The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.


function sattoloCycle(items) {
    for (var i = items.length-1; i > 0; i--) {
        var j = Math.floor(Math.random() * i);
        var tmp = items[i];
        items[i] = items[j];
        items[j] = tmp;
    }
}

implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.


ES5[edit]
function median(ary) {
    if (ary.length == 0)
        return null;
    ary.sort(function (a,b){return a - b})
    var mid = Math.floor(ary.length / 2);
    if ((ary.length % 2) == 1)  // length is odd
        return ary[mid];
    else
        return (ary[mid - 1] + ary[mid]) / 2;
}

median([]);   // null
median([5,3,4]);  // 4
median([5,4,2,3]);  // 3.5
median([3,4,1,-8.4,7.2,4,1,1.2]);  // 2.1

ES6[edit]

Translation of: Haskell
(() => {
    'use strict';

    // median :: [Num] -> Num
    function median(xs) {
        // nth :: [Num] -> Int -> Maybe Num
        let nth = (xxs, n) => {
                if (xxs.length > 0) {
                    let [x, xs] = uncons(xxs),
                        [ys, zs] = partition(y => y < x, xs),
                        k = ys.length;

                    return k === n ? x : (
                        k > n ? nth(ys, n) : nth(zs, n - k - 1)
                    );
                } else return undefined;
            },
            n = xs.length;

        return even(n) ? (
            (nth(xs, div(n, 2)) + nth(xs, div(n, 2) - 1)) / 2
        ) : nth(xs, div(n, 2));
    }

    // GENERIC

    // partition :: (a -> Bool) -> [a] -> ([a], [a])
    let partition = (p, xs) =>
        xs.reduce((a, x) =>
            p(x) ? [a[0].concat(x), a[1]] : [a[0], a[1].concat(x)], [
                [],
                []
            ]),

        // uncons :: [a] -> Maybe (a, [a])
        uncons = xs => xs.length ? [xs[0], xs.slice(1)] : undefined,

        // even :: Integral a => a -> Bool
        even = n => n % 2 === 0,

        // div :: Num -> Num -> Int
        div = (x, y) => Math.floor(x / y);

    return [
        [],
        [5, 3, 4],
        [5, 4, 2, 3],
        [3, 4, 1, -8.4, 7.2, 4, 1, 1.2]
    ].map(median);
})();

The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. It uses the selection algorithm for efficient computation. It also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation. The calculation can be done in one go, moving (sliding window), or moving (cumulative). It uses a quick select algorithm for faster computation.


ES5[edit]
var fizzBuzz = function () {
  var i, output;
  for (i = 1; i < 101; i += 1) {
    output = '';
    if (!(i % 3)) { output += 'Fizz'; }
    if (!(i % 5)) { output += 'Buzz'; }
    console.log(output || i);//empty string is false, so we short-circuit
  }
};

for (var i = 1; i <= 100; i++) {
  console.log({
    truefalse: 'Fizz',
    falsetrue: 'Buzz',
    truetrue: 'FizzBuzz'
  }[(i%3==0) + '' + (i%5==0)] || i)
}

for(i=1;i<101;i++)console.log((x=(i%3?'':'Fizz')+(i%5?'':'Buzz'))?x:i);

for(i=1;i<101;i++)console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i)

(function rng(i) {
    return i ? rng(i - 1).concat(i) : []
})(100).map(
    function (n) {
        return n % 3 ? (
            n % 5 ? n : "Buzz"
        ) : (
            n % 5 ? "Fizz" : "FizzBuzz"
        )
    }
).join(' ')
ES6[edit]
(() => {

    // FIZZBUZZ --------------------------------------------------------------

    // fizzBuzz :: Int -> String
    const fizzBuzz = n =>
        caseOf(n, [
            [x => x % 15 === 0, "FizzBuzz"],
            [x => x % 3 === 0, "Fizz"],
            [x => x % 5 === 0, "Buzz"]
        ], n.toString());

    // GENERIC FUNCTIONS -----------------------------------------------------

    // caseOf :: a -> [(a -> Bool, b)] -> b -> b
    const caseOf = (e, pvs, otherwise) =>
        pvs.reduce((a, [p, v]) =>
            a !== otherwise ? a : (p(e) ? v : a), otherwise);

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = (m, n) =>
        Array.from({
            length: Math.floor(n - m) + 1
        }, (_, i) => m + i);

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) => xs.map(f);

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // TEST ------------------------------------------------------------------
    return unlines(
        map(fizzBuzz, enumFromTo(1, 100))
    );
})();

const factors = [[3, 'Fizz'], [5, 'Buzz']]
const fizzBuzz = num => factors.map(([factor,text]) => (num % factor)?'':text).join('') || num
const range1 = x => [...Array(x+1).keys()].slice(1)
const outputs = range1(100).map(fizzBuzz)

console.log(outputs.join('\n'))

Translation of: Python
Translation of: Haskell
(() => {
    'use strict';

    // main :: IO ()
    const main = () => {

        // FIZZBUZZ ---------------------------------------

        // fizzBuzz :: Generator [String]
        const fizzBuzz = () => {
            const fb = n => k => cycle(
                replicate(n - 1)('').concat(k)
            );
            return zipWith(
                liftA2(flip)(bool)(isNull)
            )(
                zipWith(append)(fb(3)('fizz'))(fb(5)('buzz'))
            )(fmap(str)(enumFrom(1)));
        };

        // TEST -------------------------------------------
        console.log(
            unlines(
                take(100)(
                    fizzBuzz()
                )
            )
        );
    };

    // GENERIC FUNCTIONS ----------------------------------

    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a => b => ({
        type: 'Tuple',
        '0': a,
        '1': b,
        length: 2
    });

    // append (++) :: [a] -> [a] -> [a]
    // append (++) :: String -> String -> String
    const append = xs => ys => xs.concat(ys);

    // bool :: a -> a -> Bool -> a
    const bool = f => t => p =>
        p ? t : f;

    // cycle :: [a] -> Generator [a]
    function* cycle(xs) {
        const lng = xs.length;
        let i = 0;
        while (true) {
            yield(xs[i])
            i = (1 + i) % lng;
        }
    }

    // enumFrom :: Int => Int -> [Int]
    function* enumFrom(x) {
        let v = x;
        while (true) {
            yield v;
            v = 1 + v;
        }
    }

    // flip :: (a -> b -> c) -> b -> a -> c
    const flip = f =>
        x => y => f(y)(x);

    // fmap <$> :: (a -> b) -> Gen [a] -> Gen [b]
    const fmap = f =>
        function*(gen) {
            let v = take(1)(gen);
            while (0 < v.length) {
                yield(f(v[0]))
                v = take(1)(gen)
            }
        };

    // fst :: (a, b) -> a
    const fst = tpl => tpl[0];

    // isNull :: [a] -> Bool
    // isNull :: String -> Bool
    const isNull = xs =>
        1 > xs.length;

    // Returns Infinity over objects without finite length.
    // This enables zip and zipWith to choose the shorter
    // argument when one is non-finite, like cycle, repeat etc

    // length :: [a] -> Int
    const length = xs =>
        (Array.isArray(xs) || 'string' === typeof xs) ? (
            xs.length
        ) : Infinity;

    // liftA2 :: (a0 -> b -> c) -> (a -> a0) -> (a -> b) -> a -> c
    const liftA2 = op => f => g =>
        // Lift a binary function to a composition
        // over two other functions.
        // liftA2 (*) (+ 2) (+ 3) 7 == 90
        x => op(f(x))(g(x));

    // replicate :: Int -> a -> [a]
    const replicate = n => x =>
        Array.from({
            length: n
        }, () => x);

    // snd :: (a, b) -> b
    const snd = tpl => tpl[1];

    // str :: a -> String
    const str = x => x.toString();

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n => xs =>
        'GeneratorFunction' !== xs.constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

    // The first argument is a sample of the type
    // allowing the function to make the right mapping

    // uncons :: [a] -> Maybe (a, [a])
    const uncons = xs => {
        const lng = length(xs);
        return (0 < lng) ? (
            lng < Infinity ? (
                Just(Tuple(xs[0])(xs.slice(1))) // Finite list
            ) : (() => {
                const nxt = take(1)(xs);
                return 0 < nxt.length ? (
                    Just(Tuple(nxt[0])(xs))
                ) : Nothing();
            })() // Lazy generator
        ) : Nothing();
    };

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // zipWith :: (a -> b -> c) Gen [a] -> Gen [b] -> Gen [c]
    const zipWith = f => ga => gb => {
        function* go(ma, mb) {
            let
                a = ma,
                b = mb;
            while (!a.Nothing && !b.Nothing) {
                let
                    ta = a.Just,
                    tb = b.Just
                yield(f(fst(ta))(fst(tb)));
                a = uncons(snd(ta));
                b = uncons(snd(tb));
            }
        }
        return go(uncons(ga), uncons(gb));
    };

    // MAIN ---
    return main();
})();

print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.


Works with: Firefox version 3.5.11

function mandelIter(cx, cy, maxIter) {
  var x = 0.0;
  var y = 0.0;
  var xx = 0;
  var yy = 0;
  var xy = 0;

  var i = maxIter;
  while (i-- && xx + yy <= 4) {
    xy = x * y;
    xx = x * x;
    yy = y * y;
    x = xx - yy + cx;
    y = xy + xy + cy;
  }
  return maxIter - i;
}

function mandelbrot(canvas, xmin, xmax, ymin, ymax, iterations) {
  var width = canvas.width;
  var height = canvas.height;

  var ctx = canvas.getContext('2d');
  var img = ctx.getImageData(0, 0, width, height);
  var pix = img.data;

  for (var ix = 0; ix < width; ++ix) {
    for (var iy = 0; iy < height; ++iy) {
      var x = xmin + (xmax - xmin) * ix / (width - 1);
      var y = ymin + (ymax - ymin) * iy / (height - 1);
      var i = mandelIter(x, y, iterations);
      var ppos = 4 * (width * iy + ix);

      if (i > iterations) {
        pix[ppos] = 0;
        pix[ppos + 1] = 0;
        pix[ppos + 2] = 0;
      } else {
        var c = 3 * Math.log(i) / Math.log(iterations - 1.0);

        if (c < 1) {
          pix[ppos] = 255 * c;
          pix[ppos + 1] = 0;
          pix[ppos + 2] = 0;
        }
        else if ( c < 2 ) {
          pix[ppos] = 255;
          pix[ppos + 1] = 255 * (c - 1);
          pix[ppos + 2] = 0;
        } else {
          pix[ppos] = 255;
          pix[ppos + 1] = 255;
          pix[ppos + 2] = 255 * (c - 2);
        }
      }
      pix[ppos + 3] = 255;
    }
  }

  ctx.putImageData(img, 0, 0);
}

var canvas = document.createElement('canvas');
canvas.width = 900;
canvas.height = 600;

document.body.insertBefore(canvas, document.body.childNodes[0]);

mandelbrot(canvas, -2, 1, -1, 1, 1000);

generate and draw the Mandelbrot set using various algorithms and functions. The code is compatible with modern browsers supporting HTML 5 canvas tag and can be executed directly from the Javascript console. It also utilizes ES6 and WebAssembly for improved performance, requiring a compiled WASM file.


ES5[edit]
var array = [1, 2, 3, 4, 5],
    sum = 0,
    prod = 1,
    i;
for (i = 0; i < array.length; i += 1) {
    sum += array[i];
    prod *= array[i];
}
alert(sum + ' ' + prod);

Works with: Javascript version 1.8

var array = [1, 2, 3, 4, 5],
    sum = array.reduce(function (a, b) {
        return a + b;
    }, 0),
    prod = array.reduce(function (a, b) {
        return a * b;
    }, 1);
alert(sum + ' ' + prod);

ES6[edit]
(() => {
    'use strict';

    // sum :: (Num a) => [a] -> a
    const sum = xs => xs.reduce((a, x) => a + x, 0);

    // product :: (Num a) => [a] -> a
    const product = xs => xs.reduce((a, x) => a * x, 1);

    // TEST
    // show :: a -> String
    const show = x => JSON.stringify(x, null, 2);

    return show(
        [sum, product]
        .map(f => f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
    );
})();

Calculates the sum and product of all integers in an array.


var isLeapYear = function (year) { return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0); };

// Month values start at 0, so 1 is for February
var isLeapYear = function (year) { return new Date(year, 1, 29).getDate() === 29; };

determine if a given year is a leap year in the Gregorian calendar by setting the day to the 29th and checking if the day remains.


ES5[edit]

(function () {
    'use strict';

    // concatMap :: (a -> [b]) -> [a] -> [b]
    function concatMap(f, xs) {
        return [].concat.apply([], xs.map(f));
    };

    return '(Police, Sanitation, Fire)\n' +
        concatMap(function (x) {
            return concatMap(function (y) {
                return concatMap(function (z) {
                    return z !== y && 1 <= z && z <= 7 ? [
                        [x, y, z]
                    ] : [];
                }, [12 - (x + y)]);
            }, [1, 2, 3, 4, 5, 6, 7]);
        }, [2, 4, 6])
        .map(JSON.stringify)
        .join('\n');
})();

generate all possible unique combinations of numbers between 1 and 7 for three departments - police, sanitation, and fire, such that the sum of the numbers is 12 and the number for the police department is even.


var container = {myString: "Hello"};
var containerCopy = container; // Now both identifiers refer to the same object

containerCopy.myString = "Goodbye"; // container.myString will also return "Goodbye"

var a = "Hello";
var b = a; // Same as saying window.b = window.a

b = "Goodbye" // b contains a copy of a's value and a will still return "Hello"

demonstrate how to copy a string in JavaScript, distinguishing between copying the string's content and creating an additional reference to the existing string. It also illustrates that changes to one string will reflect in the other when copied via reassignment, and only the value, not the reference, will be copied when copying properties of global objects like window in browsers.


function f(num) {
 return (num === 0) ? 1 : num - m(f(num - 1));
}

function m(num) {
 return (num === 0) ? 0 : num - f(m(num - 1));
}

function range(m, n) {
  return Array.apply(null, Array(n - m + 1)).map(
    function (x, i) { return m + i; }
  );
}

var a = range(0, 19);

//return a new array of the results and join with commas to print
console.log(a.map(function (n) { return f(n); }).join(', '));
console.log(a.map(function (n) { return m(n); }).join(', '));

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions follow the defined rules: F(0) = 1, M(0) = 0, F(n) = n - M(F(n - 1)) for n > 0, and M(n) = n - F(M(n - 1)) for n > 0. If the programming language does not support mutual recursion, it is stated instead of providing a different solution.


var array = [1,2,3];
return array[Math.floor(Math.random() * array.length)];

demonstrate how to select a random element from a list.


provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


ES5[edit]

function binary_search_recursive(a, value, lo, hi) {
  if (hi < lo) { return null; }

  var mid = Math.floor((lo + hi) / 2);

  if (a[mid] > value) {
    return binary_search_recursive(a, value, lo, mid - 1);
  }
  if (a[mid] < value) {
    return binary_search_recursive(a, value, mid + 1, hi);
  }
  return mid;
}

function binary_search_iterative(a, value) {
  var mid, lo = 0,
      hi = a.length - 1;

  while (lo <= hi) {
    mid = Math.floor((lo + hi) / 2);

    if (a[mid] > value) {
      hi = mid - 1;
    } else if (a[mid] < value) {
      lo = mid + 1;
    } else {
      return mid;
    }
  }
  return null;
}

ES6[edit]

(() => {
    'use strict';

    const main = () => {

        // findRecursive :: a -> [a] -> Either String Int
        const findRecursive = (x, xs) => {
            const go = (lo, hi) => {
                if (hi < lo) {
                    return Left('not found');
                } else {
                    const
                        mid = div(lo + hi, 2),
                        v = xs[mid];
                    return v > x ? (
                        go(lo, mid - 1)
                    ) : v < x ? (
                        go(mid + 1, hi)
                    ) : Right(mid);
                }
            };
            return go(0, xs.length);
        };

        // findRecursive :: a -> [a] -> Either String Int
        const findIter = (x, xs) => {
            const [m, l, h] = until(
                ([mid, lo, hi]) => lo > hi || lo === mid,
                ([mid, lo, hi]) => {
                    const
                        m = div(lo + hi, 2),
                        v = xs[m];
                    return v > x ? [
                        m, lo, m - 1
                    ] : v < x ? [
                        m, m + 1, hi
                    ] : [m, m, hi];
                },
                [div(xs.length / 2), 0, xs.length - 1]
            );
            return l > h ? (
                Left('not found')
            ) : Right(m);
        };

        // TESTS ------------------------------------------

        const
            // (pre-sorted AZ)
            xs = ["alpha", "beta", "delta", "epsilon", "eta", "gamma",
                "iota", "kappa", "lambda", "mu", "nu", "theta", "zeta"
            ];
        return JSON.stringify([
            'Recursive',
            map(x => either(
                    l => "'" + x + "' " + l,
                    r => "'" + x + "' found at index " + r,
                    findRecursive(x, xs)
                ),
                knuthShuffle(['cape'].concat(xs).concat('cairo'))
            ),
            '',
            'Iterative:',
            map(x => either(
                    l => "'" + x + "' " + l,
                    r => "'" + x + "' found at index " + r,
                    findIter(x, xs)
                ),
                knuthShuffle(['cape'].concat(xs).concat('cairo'))
            )
        ], null, 2);
    };

    // GENERIC FUNCTIONS ----------------------------------

    // Left :: a -> Either a b
    const Left = x => ({
        type: 'Either',
        Left: x
    });

    // Right :: b -> Either a b
    const Right = x => ({
        type: 'Either',
        Right: x
    });

    // div :: Int -> Int -> Int
    const div = (x, y) => Math.floor(x / y);

    // either :: (a -> c) -> (b -> c) -> Either a b -> c
    const either = (fl, fr, e) =>
        'Either' === e.type ? (
            undefined !== e.Left ? (
                fl(e.Left)
            ) : fr(e.Right)
        ) : undefined;

    // Abbreviation for quick testing

    // enumFromTo :: (Int, Int) -> [Int]
    const enumFromTo = (m, n) =>
        Array.from({
            length: 1 + n - m
        }, (_, i) => m + i);

    // FOR TESTS

    // knuthShuffle :: [a] -> [a]
    const knuthShuffle = xs => {
        const swapped = (iFrom, iTo, xs) =>
            xs.map(
                (x, i) => iFrom !== i ? (
                    iTo !== i ? x : xs[iFrom]
                ) : xs[iTo]
            );
        return enumFromTo(0, xs.length - 1)
            .reduceRight((a, i) => {
                const iRand = randomRInt(0, i)();
                return i !== iRand ? (
                    swapped(i, iRand, a)
                ) : a;
            }, xs);
    };

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) =>
        (Array.isArray(xs) ? (
            xs
        ) : xs.split('')).map(f);

    // FOR TESTS

    // randomRInt :: Int -> Int -> IO () -> Int
    const randomRInt = (low, high) => () =>
        low + Math.floor(
            (Math.random() * ((high - low) + 1))
        );

    // reverse :: [a] -> [a]
    const reverse = xs =>
        'string' !== typeof xs ? (
            xs.slice(0).reverse()
        ) : xs.split('').reverse().join('');

    // until :: (a -> Bool) -> (a -> a) -> a -> a
    const until = (p, f, x) => {
        let v = x;
        while (!p(v)) v = f(v);
        return v;
    };

    // MAIN ---
    return main();
})();

The code implements a binary search algorithm that searches for a specific "secret" value within a sorted integer array. The search can be performed both recursively and iteratively. The algorithm divides the search range in half repeatedly until the secret value is found or the range is exhausted. The code also handles multiple values equal to the given value and indicates whether the element was found or not. It returns the index of the secret value if found, otherwise, it returns the insertion point. The code also includes variations of the binary search algorithm that return the leftmost and rightmost insertion points. Additionally, the code avoids overflow bugs during the calculation of the mid-point of the search range.


Works with: Node.js
process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});

Works with: JScript
var objArgs = WScript.Arguments;
for (var i = 0; i < objArgs.length; i++)
   WScript.Echo(objArgs.Item(i));

Works with: JScript.NET (compiled with jsc.exe)
import System;
var argv:String[] = Environment.GetCommandLineArgs();
for (var i in argv)
  print(argv[i]);

Works with: Rhino
Works with: SpiderMonkey
for (var i = 0; i < arguments.length; i++)
    print(arguments[i]);

The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c "alpha beta" -h "gamma"'. It also includes functionalities for intelligent parsing of these arguments.


With <canvas>[edit]
Translation of: E (plus gratuitous motion blur)

  <title>Pendulum</title>

<canvas id="canvas" width="600" height="600">

Sorry, your browser does not support the <canvas> used to display the pendulum animation.

</canvas>

Within SVG[edit]

<svg height="100%" width="100%" viewBox="-2 0 4 4" xmlns="http://www.w3.org/2000/svg">
  <line id="string" x1="0" y1="0" x2="1" y2="0" stroke="grey" stroke-width="0.05" />
  <circle id="ball" cx="0" cy="0" r="0.1" fill="black" />

</svg>

simulate and animate a simple gravity pendulum using SVG. The animation is created using a stereographic projection of the circle and the Euler-Lagrange equations are integrated using the Runge-Kutta method. The problem is formulated in a dimensionless manner, assuming unit values for mass and length.


var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }');

var sample = { "blue": [1,2], "ocean": "water" };
var json_string = JSON.stringify(sample);

The code loads a JSON string into a data structure and creates a new data structure, serializing it into valid JSON using objects and arrays. It requires a JSON library, which is available in all major browsers. The JSON used is different from JavaScript object literal.


function nthRoot(num, nArg, precArg) {
  var n = nArg || 2;
  var prec = precArg || 12;

  var x = 1; // Initial guess.
  for (var i=0; i<prec; i++) {
    x = 1/n * ((n-1)*x + (num / Math.pow(x, n-1)));
  }

  return x;
}

Implement the algorithm to compute the principal nth root of a positive real number with a default precision of 12 and n defaulting to 2.


Works with: JScript
var network = new ActiveXObject('WScript.Network');
var hostname = network.computerName;
WScript.echo(hostname);

"Determines and outputs the hostname of the current system where the routine is running."


generates the first 25 Leonardo numbers starting from L(0), allows customization of the first two Leonardo numbers and the add number, and can also generate the Fibonacci sequence by setting 0 and 1 for L(0) and L(1), and 0 for the add number.


function twentyfour(numbers, input) {
    var invalidChars = /[^\d\+\*\/\s-\(\)]/;

    var validNums = function(str) {
        // Create a duplicate of our input numbers, so that
        // both lists will be sorted.
        var mnums = numbers.slice();
        mnums.sort();

        // Sort after mapping to numbers, to make comparisons valid.
        return str.replace(/[^\d\s]/g, " ")
            .trim()
            .split(/\s+/)
            .map(function(n) { return parseInt(n, 10); })
            .sort()
            .every(function(v, i) { return v === mnums[i]; });
    };

    var validEval = function(input) {
        try {
            return eval(input);
        } catch (e) {
            return {error: e.toString()};
        }
    };

    if (input.trim() === "") return "You must enter a value.";
    if (input.match(invalidChars)) return "Invalid chars used, try again. Use only:\n + - * / ( )";
    if (!validNums(input)) return "Wrong numbers used, try again.";
    var calc = validEval(input);
    if (typeof calc !== 'number') return "That is not a valid input; please try again.";
    if (calc !== 24) return "Wrong answer: " + String(calc) + "; please try again.";
    return input + " == 24.  Congratulations!";
};

// I/O below.

while (true) {
    var numbers = [1, 2, 3, 4].map(function() {
        return Math.floor(Math.random() * 8 + 1);
    });

    var input = prompt(
        "Your numbers are:\n" + numbers.join(" ") +
        "\nEnter expression. (use only + - * / and parens).\n", +"'x' to exit.", "");

    if (input === 'x') {
        break;
    }
    alert(twentyfour(numbers, input));
}

"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits."


ES5[edit]

function encode(input) {
    var encoding = [];
    var prev, count, i;
    for (count = 1, prev = input[0], i = 1; i < input.length; i++) {
        if (input[i] != prev) {
            encoding.push([count, prev]);
            count = 1;
            prev = input[i];
        }
        else
            count ++;
    }
    encoding.push([count, prev]);
    return encoding;
}

Here's an encoding method that uses a regular expression to grab the character runs (Works with: JavaScript version 1.6 for the forEach method)
function encode_re(input) {
    var encoding = [];
    input.match(/(.)\1*/g).forEach(function(substr){ encoding.push([substr.length, substr[0]]) });
    return encoding;
}

function decode(encoded) {
    var output = "";
    encoded.forEach(function(pair){ output += new Array(1+pair[0]).join(pair[1]) })
    return output;
}

ES6[edit]

(() => {
    'use strict';

    // runLengthEncode :: String -> [(Int, Char)]
    const runLengthEncoded = s =>
        group(s.split('')).map(
            cs => [cs.length, cs[0]]
        );

    // runLengthDecoded :: [(Int, Char)] -> String
    const runLengthDecoded = pairs =>
        pairs.map(([n, c]) => c.repeat(n)).join('');

    // ------------------------TEST------------------------
    const main = () => {
        const
            xs = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWW' +
            'WWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW',
            ys = runLengthEncoded(xs);

        console.log('From: ', show(xs));
        [ys, runLengthDecoded(ys)].forEach(
            x => console.log('  ->  ', show(x))
        )
    };

    // ----------------------GENERIC-----------------------

    // group :: [a] -> [[a]]
    const group = xs => {
        // A list of lists, each containing only equal elements,
        // such that the concatenation of these lists is xs.
        const go = xs =>
            0 < xs.length ? (() => {
                const
                    h = xs[0],
                    i = xs.findIndex(x => h !== x);
                return i !== -1 ? (
                    [xs.slice(0, i)].concat(go(xs.slice(i)))
                ) : [xs];
            })() : [];
        return go(xs);
    };

    // show :: a -> String
    const show = JSON.stringify;

    // MAIN ---
    return main();
})();

implement a run-length encoding and decoding system. It compresses strings by counting the number of repeated characters and then reverses the compression. The input is a string of uppercase characters, and the output is a string representing the count and character. The code also includes a method that traverses the input string character by character for encoding, and a function for decoding. A generic group function and a .reduce() based one-liner are also defined.


Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


var normal = 'http://foo/bar/';
var encoded = encodeURIComponent(normal);

The code provides a function to convert a given string into URL encoding representation. It converts all characters except 0-9, A-Z, and a-z into a percent symbol followed by a two-digit hexadecimal code. It also handles ASCII control codes, symbols, and extended characters. The code also supports variations like lowercase escapes and different encoding standards like RFC 3986, HTML 5, and encodeURI function in Javascript. An optional feature to use an exception string is also provided.


generates a common sorted list with unique elements from multiple integer arrays.


ES5[edit]
Works with: Node.js
var fs = require('fs');
var words = fs.readFileSync('unixdict.txt', 'UTF-8').split('\n');

var i, item, max = 0,
    anagrams = {};

for (i = 0; i < words.length; i += 1) {
  var key = words[i].split('').sort().join('');
  if (!anagrams.hasOwnProperty(key)) {//check if property exists on current obj only
      anagrams[key] = [];
  }
  var count = anagrams[key].push(words[i]); //push returns new array length
  max = Math.max(count, max);
}

//note, this returns all arrays that match the maximum length
for (item in anagrams) {
  if (anagrams.hasOwnProperty(item)) {//check if property exists on current obj only
    if (anagrams[item].length === max) {
        console.log(anagrams[item].join(' '));
    }
  }
}

Code summarization: The code uses JavaScript for Automation on macOS to find sets of words from a given word list that are anagrams, i.e., they share the same characters but in different orders. The code specifically identifies the sets with the most words.


ES5[edit]

Translation of: Ruby
Works with: JavaScript version 1.6
Works with: Firefox version 1.5+

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Sierpinski Carpet</title>

generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation is created using a N by N array of boolean values, which are then mapped to lines of characters for output. The code also allows for the generation of a graphical representation via HTML and CSS in a browser environment. The placement of whitespace and non-whitespace characters is crucial in the representation.


Translation of: Ruby
Works with: SpiderMonkey for the print() function.

function HuffmanEncoding(str) {
    this.str = str;

    var count_chars = {};
    for (var i = 0; i < str.length; i++)
        if (str[i] in count_chars)
            count_chars[str[i]] ++;
        else
            count_chars[str[i]] = 1;

    var pq = new BinaryHeap(function(x){return x[0];});
    for (var ch in count_chars)
        pq.push([count_chars[ch], ch]);

    while (pq.size() > 1) {
        var pair1 = pq.pop();
        var pair2 = pq.pop();
        pq.push([pair1[0]+pair2[0], [pair1[1], pair2[1]]]);
    }

    var tree = pq.pop();
    this.encoding = {};
    this._generate_encoding(tree[1], "");

    this.encoded_string = ""
    for (var i = 0; i < this.str.length; i++) {
        this.encoded_string += this.encoding[str[i]];
    }
}

HuffmanEncoding.prototype._generate_encoding = function(ary, prefix) {
    if (ary instanceof Array) {
        this._generate_encoding(ary[0], prefix + "0");
        this._generate_encoding(ary[1], prefix + "1");
    }
    else {
        this.encoding[ary] = prefix;
    }
}

HuffmanEncoding.prototype.inspect_encoding = function() {
    for (var ch in this.encoding) {
        print("'" + ch + "': " + this.encoding[ch])
    }
}

HuffmanEncoding.prototype.decode = function(encoded) {
    var rev_enc = {};
    for (var ch in this.encoding)
        rev_enc[this.encoding[ch]] = ch;

    var decoded = "";
    var pos = 0;
    while (pos < encoded.length) {
        var key = ""
        while (!(key in rev_enc)) {
            key += encoded[pos];
            pos++;
        }
        decoded += rev_enc[key];
    }
    return decoded;
}

var s = "this is an example for huffman encoding";
print(s);

var huff = new HuffmanEncoding(s);
huff.inspect_encoding();

var e = huff.encoded_string;
print(e);

var t = huff.decode(e);
print(t);

print("is decoded string same as original? " + (s==t));

The code implements Huffman encoding for a given string. It first calculates the frequency of each character in the string. It then uses a binary heap to create a tree of nodes, where each node represents a character and its frequency. The tree is constructed such that nodes with lower frequencies are higher up in the tree. The code then traverses the tree from root to leaves, assigning a '0' for one branch and a '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for the corresponding character. The output is a table of characters and their Huffman encodings.


    <title>Simple Window Application</title>

 &nbsp &nbsp &nbsp &nbsp

    <button type="button" onclick="count_clicks()"> Click me</button>

    Clicks: 0

create a windowed application with a label and a button. The label initially displays "There have been no clicks yet". The button is labeled "click me". The label updates to show the number of times the button has been clicked when the button is clicked.


for (var i=10; i>=0; --i) print(i);

for (var i = 11; i--;) console.log(i);

var i = 11;
while (i--) console.log(i);

function range(m, n) {
  return Array.apply(null, Array(n - m + 1)).map(
    function (x, i) {
      return m + i;
    }
  );
}

range(0, 10).reverse().forEach(
  function (x) {
    console.log(x);
  }
);

console.log(
  range(0, 10).reverse().map(
    function (x) {
      return x;
    }
  ).join('\n')
);

console.log(
    range(0, 10).reverse().join('\n')
);

utilize a for loop to perform a countdown from 10 to 0. The code may be optimized for longer reversed iterations by moving the mutation into the test and omitting the third term of the for() statement. The code can also be written in a functional idiom of JavaScript using Array.map() instead of Array.forEach() for a composable expression with a value.


// helpers
// helper
function ordA(a) {
  return a.charCodeAt(0) - 65;
}

// vigenere
function vigenere(text, key, decode) {
  var i = 0, b;
  key = key.toUpperCase().replace(/[^A-Z]/g, '');
  return text.toUpperCase().replace(/[^A-Z]/g, '').replace(/[A-Z]/g, function(a) {
    b = key[i++ % key.length];
    return String.fromCharCode(((ordA(a) + (decode ? 26 - ordA(b) : ordA(b))) % 26 + 65));
  });
}

// example
var text = "The quick brown fox Jumped over the lazy Dog the lazy dog lazy dog dog";
var key = 'alex';
var enc = vigenere(text,key);
var dec = vigenere(enc,key,true);

console.log(enc);
console.log(dec);

Implement both encryption and decryption of a Vigenère cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.


var output = '',
    i;
for (i = 2; i <= 8; i += 2) {
   output += i + ', ';
}
output += 'who do we appreciate?';
document.write(output);

// range(iMax)
// range(iMin, iMax)
// range(iMin, iMax, dI)
function range() {
  var lngArgs = arguments.length,
    lngMore = lngArgs - 1;

  iMin = lngMore ? arguments[0] : 1;
  iMax = arguments[lngMore ? 1 : 0];
  dI = lngMore > 1 ? arguments[2] : 1;

  return lngArgs ? Array.apply(null, Array(
    Math.floor((iMax - iMin) / dI) + 1
  )).map(function (_, i) {
    return iMin + (dI * i);
  }) : [];
}

console.log(
  range(2, 8, 2).join(', ') + ', who do we appreciate ?'
);

2, 4, 6, 8, who do we appreciate ?

demonstrate a for-loop in JavaScript with a step-value greater than one, using a functional idiom. The computation is composed within the superordinate expressions of the program, returning a value rather than firing off side-effects. The stepped series is generated as an expression, replacing a state-changing loop with a non-mutating map or fold.


Translation of: C

var obj;

function sum(o, lo, hi, term) {
  var tmp = 0;
  for (o.val = lo; o.val <= hi; o.val++)
    tmp += term();
  return tmp;
}

obj = {val: 0};
alert(sum(obj, 1, 100, function() {return 1 / obj.val}));

The code implements Jensen's Device, a programming technique that exploits the call by name mechanism. It calculates the 100th harmonic number using a sum procedure, which takes in four parameters: an integer, two range values, and a term passed by name. The sum procedure iteratively adds the term to a temporary variable, which is then returned as the result. The calculation depends on the re-evaluation of the passed expression in the caller's context each time the formal parameter's value is needed. The first parameter, representing the bound variable of the summation, is also passed by name to ensure changes to it are visible in the caller's context. The result is displayed as '5.187377517639621'.


Translation of: J
function maze(x,y) {
	var n=x*y-1;
	if (n<0) {alert("illegal maze dimensions");return;}
	var horiz =[]; for (var j= 0; j<x+1; j++) horiz[j]= [],
	    verti =[]; for (var j= 0; j<x+1; j++) verti[j]= [],
	    here = [Math.floor(Math.random()*x), Math.floor(Math.random()*y)],
	    path = [here],
	    unvisited = [];
	for (var j = 0; j<x+2; j++) {
		unvisited[j] = [];
		for (var k= 0; k<y+1; k++)
			unvisited[j].push(j>0 && j<x+1 && k>0 && (j != here[0]+1 || k != here[1]+1));
	}
	while (0<n) {
		var potential = [[here[0]+1, here[1]], [here[0],here[1]+1],
		    [here[0]-1, here[1]], [here[0],here[1]-1]];
		var neighbors = [];
		for (var j = 0; j < 4; j++)
			if (unvisited[potential[j][0]+1][potential[j][1]+1])
				neighbors.push(potential[j]);
		if (neighbors.length) {
			n = n-1;
			next= neighbors[Math.floor(Math.random()*neighbors.length)];
			unvisited[next[0]+1][next[1]+1]= false;
			if (next[0] == here[0])
				horiz[next[0]][(next[1]+here[1]-1)/2]= true;
			else
				verti[(next[0]+here[0]-1)/2][next[1]]= true;
			path.push(here = next);
		} else
			here = path.pop();
	}
	return {x: x, y: y, horiz: horiz, verti: verti};
}

function display(m) {
	var text= [];
	for (var j= 0; j<m.x*2+1; j++) {
		var line= [];
		if (0 == j%2)
			for (var k=0; k<m.y*4+1; k++)
				if (0 == k%4)
					line[k]= '+';
				else
					if (j>0 && m.verti[j/2-1][Math.floor(k/4)])
						line[k]= ' ';
					else
						line[k]= '-';
		else
			for (var k=0; k<m.y*4+1; k++)
				if (0 == k%4)
					if (k>0 && m.horiz[(j-1)/2][k/4-1])
						line[k]= ' ';
					else
						line[k]= '|';
				else
					line[k]= ' ';
		if (0 == j) line[1]= line[2]= line[3]= ' ';
		if (m.x*2-1 == j) line[4*m.y]= ' ';
		text.push(line.join('')+'\r\n');
	}
	return text.join('');
}

x,y — dimensions of maze
n — number of openings to be generated
horiz — two dimensional array of locations of horizontal openings (true means wall is open)
verti — two dimensional array of locations of vertical openings (true means wall is open)
here — current location under consideration
path — history (stack) of locations that might need to be revisited
unvisited — two dimensional array of locations that have not been visited, padded to avoid need for boundary tests (true means location needs to be visited)
potential — locations adjacent to here
neighbors — unvisited locations adjacent to here

m — maze to be drawn
text — lines of text representing maze
line — characters of current line

Example use:
<title></title>

+   +---+---+---+---+---+---+---+---+---+---+
|                   |                   |   |
+---+---+   +   +---+   +   +---+---+   +   +
|       |   |   |       |   |           |   |
+   +   +   +---+   +---+   +---+---+   +   +
|   |   |               |           |   |   |
+   +---+   +---+---+---+---+---+   +   +   +
|       |   |               |       |       |
+---+   +---+   +---+---+   +   +---+---+   +
|   |   |       |               |       |   |
+   +   +   +---+---+---+---+---+   +   +   +
|       |                   |       |   |   |
+   +---+---+   +---+---+   +   +---+---+   +
|   |       |   |           |       |       |
+   +   +   +---+   +---+---+   +   +   +---+
|       |           |           |
+---+---+---+---+---+---+---+---+---+---+---+

	function step() {
		if (0<n) {

			document.getElementById('out').innerHTML= display({x: x, y: y, horiz: horiz, verti: verti, here: here});
			setTimeout(step, 100);
		}
	}
	step();

				if (m.here && m.here[0]*2+1 == j && m.here[1]*4+2 == k)
					line[k]= '#'
				else if (0 == k%4) {

			here= next;
			if (1 < neighbors.length)
				path.push(here);

HTML Table[edit]

<title>Maze maker</title>

<form><fieldset>
rows <input id='rows' size="3"/>
colums <input id='cols' size="3"/>
Generate
Solve
</fieldset></form>

The code generates and displays a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and proceeds to its neighbors. If a neighbor hasn't been visited, the wall between the current cell and that neighbor is removed and the process is repeated for that neighbor. The code relies on JavaScript arrays' ability to be treated as infinite in size with null values appearing as needed. The progress of the maze creation can be animated by using a display function in each iteration of the main loop. The code also suggests an optimization to save processing, but it will still need to backtrack through locations with no unvisited neighbors. The maze is displayed using HTML, CSS, and table cells.


Spigot Algorithm[edit]

let q = 1n, r = 180n, t = 60n, i = 2n;
for (;;) {
  let y = (q*(27n*i-12n)+5n*r)/(5n*t);
  let u = 3n*(3n*i+1n)*(3n*i+2n);
  r = 10n*u*(q*(5n*i-2n)+r-y*t);
  q = 10n*q*i*(2n*i-1n);
  t = t*u;
  i = i+1n;
  process.stdout.write(y.toString());
  if (i === 3n) { process.stdout.write('.'); }
}

Web Page version[edit]

<tt id="pi"></tt><tt>...</tt>

Web Page using BigInt[edit]

  <tt id="pi"></tt>
  <tt>...</tt>

Simple Approximation[edit]

var calcPi = function() {
  var n = 20000;
  var pi = 0;
  for (var i = 0; i < n; i++) {
    var temp = 4 / (i*2+1);
    if (i % 2 == 0) {
      pi += temp;
    }
    else {
      pi -= temp;
    }
  }
  return pi;
}

The code continuously calculates and outputs the next decimal digit of Pi, starting from 3.14159265... until manually stopped by the user. It can be adapted to work in both Node.js and browser environments. It also includes a feature to load the code into a webpage without freezing the browser. The code uses BigInt and may consume significant memory. It returns an approximation of Pi, calculated one digit at a time.


"Function to compare and order two numerical lists based on lexicographic order, returning true if the first list should be ordered before the second, false otherwise."


ES5[edit]
function ack(m, n) {
 return m === 0 ? n + 1 : ack(m - 1, n === 0  ? 1 : ack(m, n - 1));
}

Eliminating Tail Calls[edit]
function ack(M,N) {
  for (; M > 0; M--) {
    N = N === 0 ? 1 : ack(M,N-1);
  }
  return N+1;
}

Iterative, With Explicit Stack[edit]
function stackermann(M, N) {
  const stack = [];
  for (;;) {
    if (M === 0) {
      N++;
      if (stack.length === 0) return N;
      const r = stack[stack.length-1];
      if (r[1] === 1) stack.length--;
      else r[1]--;
      M = r[0];
    } else if (N === 0) {
      M--;
      N = 1;
    } else {
      M--
      stack.push([M, N]);
      N = 1;
    }
  }
}

Stackless Iterative[edit]
#!/usr/bin/env nodejs
function ack(M, N){
	const next = new Float64Array(M + 1);
	const goal = new Float64Array(M + 1).fill(1, 0, M);
	const n = N + 1;

	// This serves as a sentinel value;
	// next[M] never equals goal[M] == -1,
	// so we don't need an extra check for
	// loop termination below.
	goal[M] = -1;

	let v;
	do {
		v = next[0] + 1;
		let m = 0;
		while (next[m] === goal[m]) {
			goal[m] = v;
			next[m++]++;
		}
		next[m]++;
	} while (next[M] !== n);
	return v;
}
var args = process.argv;
console.log(ack(parseInt(args[2]), parseInt(args[3])));

Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.


Implement and compare the Gamma function using built-in/library function and self-implemented algorithms. The function is defined through numerical integration, and methods include Lanczos and Stirling's approximation.


ES5[edit]

function queenPuzzle(rows, columns) {
    if (rows <= 0) {
        return [[]];
    } else {
        return addQueen(rows - 1, columns);
    }
}

function addQueen(newRow, columns, prevSolution) {
    var newSolutions = [];
    var prev = queenPuzzle(newRow, columns);
    for (var i = 0; i < prev.length; i++) {
        var solution = prev[i];
        for (var newColumn = 0; newColumn < columns; newColumn++) {
            if (!hasConflict(newRow, newColumn, solution))
                newSolutions.push(solution.concat([newColumn]))
        }
    }
    return newSolutions;
}

function hasConflict(newRow, newColumn, solution) {
    for (var i = 0; i < newRow; i++) {
        if (solution[i]     == newColumn          ||
            solution[i] + i == newColumn + newRow ||
            solution[i] - i == newColumn - newRow) {
                return true;
        }
    }
    return false;
}

console.log(queenPuzzle(8,8));

ES6[edit]

(() => {
    "use strict";

    // ---------------- N QUEENS PROBLEM -----------------

    // queenPuzzle :: Int -> Int -> [[Int]]
    const queenPuzzle = intCols => {
        // All solutions for a given number
        // of columns and rows.
        const go = nRows =>
            nRows <= 0 ? [
                []
            ] : go(nRows - 1).reduce(
                (a, solution) => [
                    ...a, ...(
                        enumFromTo(0)(intCols - 1)
                        .reduce((b, iCol) =>
                            safe(
                                nRows - 1, iCol, solution
                            ) ? (
                                [...b, [...solution, iCol]]
                            ) : b, [])
                    )
                ], []
            );

        return go;
    };

    // safe : Int -> Int -> [Int] -> Bool
    const safe = (iRow, iCol, solution) =>
        !zip(solution)(
            enumFromTo(0)(iRow - 1)
        )
        .some(
            ([sc, sr]) => (iCol === sc) || (
                sc + sr === iCol + iRow
            ) || (sc - sr === iCol - iRow)
        );

    // ---------------------- TEST -----------------------
    // Ten columns of solutions to the 7*7 board

    // main :: IO ()
    const main = () =>
        // eslint-disable-next-line no-console
        console.log(
            showSolutions(10)(7)
        );

    // --------------------- DISPLAY ---------------------

    // showSolutions :: Int -> Int -> String
    const showSolutions = nCols =>
        // Display of solutions, in nCols columns
        // for a board of size N * N.
        n => chunksOf(nCols)(
            queenPuzzle(n)(n)
        )
        .map(xs => transpose(
                xs.map(
                    rows => rows.map(
                        r => enumFromTo(1)(rows.length)
                        .flatMap(
                            x => r === x ? (
                                "♛"
                            ) : "."
                        )
                        .join("")
                    )
                )
            )
            .map(cells => cells.join("  "))
        )
        .map(x => x.join("\n"))
        .join("\n\n");

    // ---------------- GENERIC FUNCTIONS ----------------

    // chunksOf :: Int -> [a] -> [[a]]
    const chunksOf = n => {
        // xs split into sublists of length n.
        // The last sublist will be short if n
        // does not evenly divide the length of xs .
        const go = xs => {
            const chunk = xs.slice(0, n);

            return Boolean(chunk.length) ? [
                chunk, ...go(xs.slice(n))
            ] : [];
        };

        return go;
    };

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = m =>
        n => Array.from({
            length: 1 + n - m
        }, (_, i) => m + i);

    // transpose_ :: [[a]] -> [[a]]
    const transpose = rows =>
        // The columns of the input transposed
        // into new rows.
        // Simpler version of transpose, assuming input
        // rows of even length.
        Boolean(rows.length) ? rows[0].map(
            (_, i) => rows.flatMap(
                v => v[i]
            )
        ) : [];

    // zip :: [a] -> [b] -> [(a, b)]
    const zip = xs =>
        // The paired members of xs and ys, up to
        // the length of the shorter of the two lists.
        ys => Array.from({
            length: Math.min(xs.length, ys.length)
        }, (_, i) => [xs[i], ys[i]]);

    // MAIN ---
    return main();
})();

implement a solution to the N-queens problem using recursive backtracking. The algorithm checks for the correct position on subfields to save position checks. It also includes a function to display columns of solutions. The code is a translation of an ES5 version. It can solve the puzzle for a board of any size NxN and provides the number of solutions for small values of N.


var a = [1,2,3],
    b = [4,5,6],
    c = a.concat(b); //=> [1,2,3,4,5,6]

Translation of: Haskell

(function () {
    'use strict';

    // concat :: [[a]] -> [a]
    function concat(xs) {
        return [].concat.apply([], xs);
    }

   return concat(
      [["alpha", "beta", "gamma"],
      ["delta", "epsilon", "zeta"],
      ["eta", "theta", "iota"]]
  );

})();

demonstrate how to concatenate two arrays using the Array.concat() method or a generic function, as per the programming task.