Earn extra honor and gain new allies!
Honor is earned for each new codewarrior who joins.
Learn more

Construct a singleton in js.

Tests:
let obj1 = new Singleton();
let obj2 = new Singleton();
obj1.test = 1;

obj1 === obj2 // true
obj2.test // 1

let Singleton = (function () {
	let instance;

	return function Construct_singletone () {
		if (instance) {
			return instance;
		}
		if (this && this.constructor === Construct_singletone) {
			instance = this;
		} else {
			return new Construct_singletone();
		}
	}
}());
Code
Diff
  • var merge = (array1, array2, callbackFN) => callbackFN(array1,array2);
    
    callbackFN = (a,b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length ?
      a.map((c, i) => c + b[i])
      : 'both inputs must be Array and same size of elements';  
    
    var x = merge([1, 3, 4], [5, 6, 7, 8], callbackFN);
    console.log(x);   //'both inputs must be Array and same size of elements'
    
    x = merge([1, 2, 3, 4], [5, 6, 7, 8], callbackFN);
    console.log(x);   //[6, 8, 10, 12].
  • 1-var merge = function(array1, array2, callbackFN){
    2- return callbackFN(array1,array2);
    3-}
    1+var merge = (array1, array2, callbackFN) => callbackFN(array1,array2);
    44
    5-function callbackFN(a,b) {
    6- if(Array.isArray(a) && Array.isArray(b) && (a.length === b.length)){
    7- return a.map(function(c,i){ return c + b[i]; });
    8- } else {
    9- return 'both inputs must be Array and same size of elements';
    10- }
    11-
    12-}
    3+callbackFN = (a,b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length ?
    4+ a.map((c, i) => c + b[i])
    5+ : 'both inputs must be Array and same size of elements';
    1313
    1414 var x = merge([1, 3, 4], [5, 6, 7, 8], callbackFN);
    15-console.log(x); //x should now equal [6, 8, 10, 12].
    8+console.log(x); //'both inputs must be Array and same size of elements'
    9+
    10+x = merge([1, 2, 3, 4], [5, 6, 7, 8], callbackFN);
    11+console.log(x); //[6, 8, 10, 12].
Code
Diff
  • Number.prototype.times = function (f) {
      for (let i = 0; i < this; i++) f(i);
    }
  • 11 Number.prototype.times = function (f) {
    2- for (let i = 0; i < this; i++) {
    3- f(i);
    4- }
    2+ for (let i = 0; i < this; i++) f(i);
    55 }
Code
Diff
  • let greetLanguage = (greeting = "Hello", language = "Javascript") => `${greeting}, ${language}!`;
  • 1-function greetLanguage(greeting = "Hello", language = "Javascript") {
    2- var result = `${greeting}, ${language}!`;
    3- console.log(result);
    4- return result;
    5-}
    1+let greetLanguage = (greeting = "Hello", language = "Javascript") => `${greeting}, ${language}!`;