exercism / javascript

Exercism exercises in JavaScript.
https://exercism.org/tracks/javascript
MIT License
580 stars 616 forks source link

Building a training set of tags for javascript #2310

Closed iHiD closed 11 months ago

iHiD commented 1 year ago

Hello lovely maintainers :wave:

We've recently added "tags" to student's solutions. These express the constructs, paradigms and techniques that a solution uses. We are going to be using these tags for lots of things including filtering, pointing a student to alternative approaches, and much more.

In order to do this, we've built out a full AST-based tagger in C#, which has allowed us to do things like detect recursion or bit shifting. We've set things up so other tracks can do the same for their languages, but its a lot of work, and we've determined that actually it may be unnecessary. Instead we think that we can use machine learning to achieve tagging with good enough results. We've fine-tuned a model that can determine the correct tags for C# from the examples with a high success rate. It's also doing reasonably well in an untrained state for other languages. We think that with only a few examples per language, we can potentially get some quite good results, and that we can then refine things further as we go.

I released a new video on the Insiders page that talks through this in more detail.

We're going to be adding a fully-fledged UI in the coming weeks that allow maintainers and mentors to tag solutions and create training sets for the neural networks, but to start with, we're hoping you would be willing to manually tag 20 solutions for this track. In this post we'll add 20 comments, each with a student's solution, and the tags our model has generated. Your mission (should you choose to accept it) is to edit the tags on each issue, removing any incorrect ones, and add any that are missing. In order to build one model that performs well across languages, it's best if you stick as closely as possible to the C# tags as you can. Those are listed here. If you want to add extra tags, that's totally fine, but please don't arbitrarily reword existing tags, even if you don't like what Erik's chosen, as it'll just make it less likely that your language gets the correct tags assigned by the neural network.


To summarise - there are two paths forward for this issue:

  1. You're up for helping: Add a comment saying you're up for helping. Update the tags some time in the next few days. Add a comment when you're done. We'll then add them to our training set and move forward.
  2. You not up for helping: No problem! Just please add a comment letting us know :)

If you tell us you're not able/wanting to help or there's no comment added, we'll automatically crowd-source this in a week or so.

Finally, if you have questions or want to discuss things, it would be best done on the forum, so the knowledge can be shared across all maintainers in all tracks.

Thanks for your help! :blue_heart:


Note: Meta discussion on the forum

iHiD commented 1 year ago

Exercise: reverse-string

Code

export const reverseString = (s) => {
    if (s == "" || s == null) { return ""; }
    else { return s.split("").reverse().join(""); }
}

Tags:

construct:boolean
construct:const
construct:double-quoted-string
construct:export
construct:fat-arrow
construct:if
construct:implicit-conversion
construct:logical-or
construct:method
construct:null
construct:null-value
construct:parameter
construct:return
construct:string
construct:throw
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:exceptions
iHiD commented 1 year ago

Exercise: simple-cipher

Code

export default class Cipher {
    constructor(key) {
        if (key !== undefined) {
            if (key !== '' && /^[a-z]+$/.test(key)) this.key = key
            else throw new Error('Bad key')
        } else {
            this.generateKey()
        }
    }
    generateKey() {
        const randomLowerLetter = () => String.fromCharCode(97 + Math.floor(Math.random() * 26))
        this.key = Array.from(Array(100), randomLowerLetter).join('')
    }
    shift(text, direction) {
        const offsetFromKey = i => this.key.charCodeAt(i % this.key.length) - 97
        const shiftChar = (char, index) => {
            let offset = (char.charCodeAt(0) - 97 + direction * offsetFromKey(index)) % 26
            if (offset < 0) offset += 26
            return String.fromCharCode(offset + 97)
        }
        return Array.from(text, shiftChar).join('')
    }
    encode(plaintext) {
        return this.shift(plaintext, 1)
    }
    decode(ciphertext) {
        return this.shift(ciphertext, -1)
    }
}

Tags:

construct:add
construct:assignment
construct:boolean
construct:class
construct:constructor
construct:const
construct:divide
construct:double
construct:else
construct:export
construct:fat-arrow-function
construct:floating-point-number
construct:if
construct:implicit-conversion
construct:invocation
construct:lambda
construct:logical-and
construct:method
construct:multiply
construct:number
construct:parameter
construct:regular-expression
construct:return
construct:string
construct:subtract
construct:throw
construct:undefined
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:exceptions
technique:higher-order-functions
technique:randomness
technique:regular-expression
uses:RegExp
iHiD commented 1 year ago

Exercise: etl

Code

var ETL = function() {
  this.transform = function(oldScoring) {
    scores = Object.keys(oldScoring);
    this.newScoring = {};
    for (var index in scores) {
      var score = scores[index];
      var letters = oldScoring[score];
      for (var index in letters) {
        var letter = letters[index].toLowerCase();
        this.newScoring[letter] = Number(score);
      }
    }
    return this.newScoring;
  };
};

module.exports = ETL;

Tags:

construct:assignment
construct:for-loop
construct:function
construct:in-place
construct:indexed-access
construct:invocation
construct:method
construct:object
construct:parameter
construct:return
construct:string
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:looping
iHiD commented 1 year ago

Exercise: perfect-numbers

Code

class PerfectNumbers {

    classify(number) {
        if (number < 1) {
            throw new Error('Classification is only possible for natural numbers.');
        }
        let sum = 0,
            factors = factorize(number);
        const reducer = (accumulator, currentValue) => accumulator + currentValue;
        if (factors.length !== 0) {
            sum = factors.reduce(reducer);
        }
        if (sum === number) {
            return 'perfect';
        }
        if (sum > number) {
            return 'abundant';
        }
        return 'deficient';
    }
}

function factorize(num) {
    var factors = [];
    let x = num - 1;
    while (x !== 0) {
        if (num % x === 0) {
            factors.push(x);
        }
        x--;
    }
    return factors;
}

export default PerfectNumbers;

Tags:

construct:assignment
construct:class
construct:const
construct:constructor
construct:export
construct:if
construct:implicit-conversion
construct:import
construct:method
construct:number
construct:parameter
construct:return
construct:string
construct:subtract
construct:throw
construct:variable
construct:visibility-modifiers
construct:while-loop
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:looping
iHiD commented 1 year ago

Exercise: allergies

Code

function Allergies(score) {

  var object = { '0': 'eggs','1': 'peanuts', '2': 'shellfish', '3': 'strawberries', '4': 'tomatoes', '5': 'chocolate', '6': 'pollen', '7': 'cats'}

  this.list = function() {
    var l = []
    if (score < 1) return l;
    for (var property in object) {
      if ( (score & 1 << property) > 0 ) {
        l.push(object[property])
      }
    }  

    return l;
  }

  this.allergicTo = function(someAllergy) {
    for (var property in object) {
      if (object[property] == someAllergy) {
        if ( (score & 1 << property) > 0 ) {
          return true;
        }
      }
    } 
    return false;
  }

};

module.exports = Allergies;

Tags:

construct:assignment
construct:bitwise-and
construct:bitwise-left-shift
construct:boolean
construct:for-loop
construct:function
construct:if
construct:implicit-conversion
construct:indexed-access
construct:method
construct:number
construct:object
construct:parameter
construct:return
construct:string
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:functional
paradigm:object-oriented
technique:bit-manipulation
technique:bit-shifting
technique:looping
iHiD commented 1 year ago

Exercise: kindergarten-garden

Code

(function() {
  'use strict';

  var Garden = function(diagram, roster) {
    this.roster = roster ? roster.sort() : DEFAULT_ROSTER;
    this.rows = diagram.split("\n");
    this.spots = spotsForClass(this.roster);

    for (var i = 0; i < this.roster.length; i++) {
      var student = this.roster[i];
      var result = this.forStudent(student);
      this[student.toLowerCase()] = result;
    };

  };

  Garden.prototype.forStudent = function(student) {
    var start = this.spots[student][0];
    var end = this.spots[student][1];

    return this.rows.map(function(row) {
      return translateRow(row, start, end);
    }).flatten();
  }

  function translateRow(row, start, end) {
    return row.split('').slice(start, end).map(function(char) {
      return translate(char);
    });
  }

  function translate(abbreviation) {
    return TRANSLATIONS[abbreviation];
  }

  function spotsForClass(roster) {
    var spots = {};
    for (var i = 0; i < roster.length; i++) {
      spots[roster[i]] = [(i * 2), ((i * 2) + 2)];
    }
    return spots;
  }

  var TRANSLATIONS = {
    'R': 'radishes',
    'C': 'clover',
    'G': 'grass',
    'V': 'violets'
  };

  var DEFAULT_ROSTER = [
    'alice',
    'bob',
    'charlie',
    'david',
    'eve',
    'fred',
    'ginny',
    'harriet',
    'ileana',
    'joseph',
    'kincaid',
    'larry'
  ];

  Array.prototype.flatten = function() {
    return this.reduce(function(a, b) {
      return a.concat(b);
    });
  };

  module.exports = Garden;
})();

Tags:

construct:add
construct:array
construct:assignment
construct:char
construct:for-loop
construct:function
construct:function-invocation
construct:if
construct:implicit-conversion
construct:index
construct:invocation
construct:lambda
construct:method
construct:multiply
construct:nested-object
construct:number
construct:object
construct:parameter
construct:property
construct:prototype
construct:return
construct:string
construct:ternary
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:higher-order-functions
technique:looping
iHiD commented 1 year ago

Exercise: house

Code

const words = {
    1: {
        noun: 'house that Jack built.',
        verb: 'lay in',
    },
    2: {
        noun: 'malt',
        verb: 'ate',
    },
    3: {
        noun: 'rat',
        verb: 'killed',
    },
    4: {
        noun: 'cat',
        verb: 'worried',
    },
    5: {
        noun: 'dog',
        verb: 'tossed',
    },
    6: {
        noun: 'cow with the crumpled horn',
        verb: 'milked',
    },
    7: {
        noun: 'maiden all forlorn',
        verb: 'kissed',
    },
    8: {
        noun: 'man all tattered and torn',
        verb: 'married',
    },
    9: {
        noun: 'priest all shaven and shorn',
        verb: 'woke',
    },
    10: {
        noun: 'rooster that crowed in the morn',
        verb: 'kept',
    },
    11: {
        noun: 'farmer sowing his corn',
        verb: 'belonged to',
    },
    12: {
        noun: 'horse and the hound and the horn',
    },
}

export default {
    getSentence(verseNum, index) {
        return verseNum === index ? `This is the ${ words[index].noun }` : `that ${ words[index].verb } the ${ words[index].noun }`;
    },
    verse(num) {
        const result = [];
        for (let i = num; i > 0; i--) {
            result.push( this.getSentence(num, i) );
        }

        return result;
    },
    verses(startVerse, endVerse) {
        let result = [];
        for (let i = startVerse; i < endVerse + 1; i++) {
            result = result.concat(this.verse(i));

            if (i !== endVerse) {
                result.push('');
            }
        }

        return result;
    },
}

Tags:

construct:string-interpolation
construct:add
construct:assignment
construct:const
construct:for-loop
construct:if
construct:indexed-access
construct:initializer
construct:invocation
construct:method
construct:number
construct:object
construct:parameter
construct:property
construct:return
construct:string
construct:ternary
construct:template-string
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:looping
iHiD commented 1 year ago

Exercise: house

Code

const VERSES = {
  1: { verb: 'that lay in ', subject: 'the house that Jack built.' },
  2: { verb: 'that ate ', subject: 'the malt' },
  3: { verb: 'that killed ', subject: 'the rat' },
  4: { verb: 'that worried ', subject: 'the cat' },
  5: { verb: 'that tossed ', subject: 'the dog' },
  6: { verb: 'that milked ', subject: 'the cow with the crumpled horn' },
  7: { verb: 'that kissed ', subject: 'the maiden all forlorn' },
  8: { verb: 'that married ', subject: 'the man all tattered and torn' },
  9: { verb: 'that woke ', subject: 'the priest all shaven and shorn' },
  10: { verb: 'that kept ', subject: 'the rooster that crowed in the morn' },
  11: { verb: 'that belonged to ', subject: 'the farmer sowing his corn' },
  12: { verb: '', subject: 'the horse and the hound and the horn' },
};

class House {
  static verses(start, end, poems = []) {
    if (start > end) { return ([].concat(...poems)).slice(0, -1); }

    poems.push(House.verse(start));
    poems.push('');

    return House.verses(start + 1, end, poems);
  }

  static verse(n, start = null, poem = []) {
    if (n === 0) { return poem; }

    if (!start) { start = n; }

    if (n === start) {
      poem.push(`This is ${VERSES[n].subject}`);
      return House.verse(n - 1, start, poem);
    }

    const thisVerse = VERSES[n];

    poem.push(thisVerse.verb + thisVerse.subject);

    return House.verse(n - 1, start, poem);
  }
}

export { House as default };

Tags:

construct:assignment
construct:class
construct:const
construct:constructor
construct:if
construct:implicit-conversion
construct:indexed-access
construct:invocation
construct:lambda
construct:method
construct:null
construct:nullability
construct:number
construct:optional-parameter
construct:parameter
construct:property
construct:return
construct:string
construct:subtract
construct:template-string
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:recursion
iHiD commented 1 year ago

Exercise: twelve-days

Code

const days = [
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
"eleventh",
"twelfth"
];
const verses = [
'and a Partridge in a Pear Tree.',
'two Turtle Doves',
'three French Hens',
'four Calling Birds',
'five Gold Rings',
'six Geese-a-Laying',
'seven Swans-a-Swimming',
'eight Maids-a-Milking',
'nine Ladies Dancing',
'ten Lords-a-Leaping',
'eleven Pipers Piping',
'twelve Drummers Drumming'
];

export default class TwelveDays{
  verse(verseA, verseB){
    if(verseB){
      return this.getMultipleVerses(verseA, verseB);
    } else {
      return this.getVerseByNumber(verseA) + "\n";
    }
  }

  sing(){
    return this.getMultipleVerses(1,12)
  }

  getVerseByNumber(verseNumber){
    let song = this.returnSongStart(verseNumber);
    if(verseNumber === 1){
      return `${song} a Partridge in a Pear Tree.`
    } else {
      while(0 < verseNumber){
        song = `${song} ${this.returnVerse(verseNumber)}`
        verseNumber--;
      }
    }
    return song;
  }

  getMultipleVerses(startVerse, endVerse){
    let finalVerse = "";
    while(startVerse <= endVerse){
      finalVerse = `${finalVerse}${this.getVerseByNumber(startVerse)}${this.returnBreaks(startVerse === endVerse)}`;
      startVerse++;
    }
    return finalVerse;
  }

  returnSongStart(num){
    return `On the ${days[num - 1]} day of Christmas my true love gave to me:`;
  }

  returnComma(num){
   return (num !== 1) ? ',' : '';
  }

  returnVerse(num){
    return verses[num - 1] + this.returnComma(num);
  }

  returnBreaks(val){
    return val ? '\n' : '\n\n';
  }
}

Tags:

construct:string-interpolation
construct:add
construct:assignment
construct:boolean
construct:class
construct:const
construct:constructor
construct:export
construct:if
construct:index
construct:initializer
construct:invocation
construct:lambda
construct:let
construct:method
construct:number
construct:parameter
construct:return
construct:string
construct:subtract
construct:ternary
construct:variable
construct:visibility-modifiers
construct:while-loop
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:higher-order-functions
technique:looping
iHiD commented 1 year ago

Exercise: legacy-hello-world

Code

//
// This is a stub file for the 'Hello World' exercise. It's been provided as a
// convenience to get you started writing code faster.
// Make sure to look at hello-world.spec.js--that should give you some hints about what is
// expected here.

var HelloWorld = function() {};

HelloWorld.prototype.hello = function(input) {
  if (input != '') {
    input = 'Hello, ' + input + '!';
  } else {
    input = 'Hello, World!';
  }
  return input;
};

module.exports = HelloWorld;

Tags:

construct:add
construct:assignment
construct:comment
construct:constructor
construct:function
construct:if
construct:method
construct:parameter
construct:prototype
construct:return
construct:string
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
iHiD commented 1 year ago

Exercise: legacy-hamming

Code

var Hamming = function() {};

Hamming.prototype.compute = function(string1, string2) {
  if (string1.length !== string2.length) {
    throw new Error("DNA strands must be of equal length.");
  }
  var count  = 0;
  for (var i = 0; i < string1.length; i++) {
    if (string1[i] !== string2[i]) count += 1;
  }
  return count;
}

module.exports = Hamming;

Tags:

construct:assignment
construct:constructor
construct:for-loop
construct:function
construct:if
construct:index
construct:method
construct:number
construct:parameter
construct:prototype
construct:return
construct:string
construct:throw
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:looping
iHiD commented 1 year ago

Exercise: legacy-food-chain

Code

'use strict';

function formatString(s) {
  var args = Array.prototype.slice.call(arguments, 1);
  return s.replace(/{(\d+)}/g, function (match, number) {
    return typeof args[number] !== 'undefined' ? args[number] : match;
  });
}

function getLastLine(endingVerseNumber){
  return (endingVerseNumber===SWALLOWED.length ? SWALLOWED[SWALLOWED.length-1].terminal : SWALLOWED[0].terminal);
}

function startsWithVowel(myString){
  return myString.match("/^[aeiou]/i");
}

function getWhatSheSwallowed(index){
  var what=SWALLOWED[index-1].what;
  return "I know an old lady who swallowed "+(startsWithVowel(what) ? "an " : "a ")+what+".";
}

function getUniqueStatement(index){
  return SWALLOWED[index-1].unique;
}

function getWhatAteWhat(index){
  var swallowed=SWALLOWED[index-1];
  var swallowedPrevious=SWALLOWED[index-2];
  var line=formatString("She swallowed the {0} to catch the {1}", swallowed.what, swallowedPrevious.what);
  line+=(swallowedPrevious.action ? swallowedPrevious.action+"." : ".");
  return line;
}

function isTerminalCreature(index) {
  return SWALLOWED[index-1].terminal;
}

var SWALLOWED = [{
  what: 'fly',
  terminal: 'I don\'t know why she swallowed the fly. Perhaps she\'ll die.'
}, {
  what: 'spider',
  unique: 'It wriggled and jiggled and tickled inside her.',
  action: ' that wriggled and jiggled and tickled inside her',
}, {
  what: 'bird',
  unique: 'How absurd to swallow a bird!'
}, {
  what: 'cat',
  unique: 'Imagine that, to swallow a cat!'
}, {
  what: 'dog',
  unique: 'What a hog, to swallow a dog!'
}, {
  what: 'goat',
  unique: 'Just opened her throat and swallowed a goat!'
}, {
  what: 'cow',
  unique: 'I don\'t know how she swallowed a cow!'
}, {
  what: 'horse',
  terminal: 'She\'s dead, of course!'
}];

function getVerse(verseNumber){
  var lines=[];
  var currentCreatureNumber=verseNumber;
  lines.push(getWhatSheSwallowed(currentCreatureNumber));
  var uniqueStatement=getUniqueStatement(currentCreatureNumber);
  if (uniqueStatement){
    lines.push(uniqueStatement);
  }

  while (!isTerminalCreature(currentCreatureNumber)){
    lines.push(getWhatAteWhat(currentCreatureNumber--));
  }

  lines.push(getLastLine(verseNumber));
  return lines.join("\n")+"\n";
}

function getVerses(startVerse, endVerse){
  var verses=[];
  for (var ii=startVerse;ii<=endVerse;ii++){
    verses.push(getVerse(ii));
  }
  return verses.join("\n")+"\n";
}

module.exports = {
  verse: getVerse,
  verses: getVerses
};

Tags:

construct:assignment
construct:boolean
construct:constructor
construct:for-loop
construct:function
construct:if
construct:implicit-conversion
construct:index
construct:invocation
construct:method
construct:number
construct:object
construct:parameter
construct:return
construct:string
construct:subtract
construct:ternary
construct:use-strict
construct:variable
construct:while-loop
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:looping
iHiD commented 1 year ago

Exercise: legacy-sieve

Code

'use strict'

/**
 * Create a new prime sieve.
 * @module Sieve
 *
 * @param {number} limit - The highest number to consider for inclusion.
 * @returns {Sieve}
 */
module.exports = function Sieve (limit) {
  /**
   * Sieved primes.
   * @typedef {Object} Sieve
   * @property {number[]} primes - List of sieved primes.
   */
  return Object.freeze({
    primes: Array.from(primeSequence(limit))
  })
}

function * primeSequence (limit) {
  if (limit < 2) return

  yield 2

  const nonprimes = new Set([])

  for (let candadate = 3; candadate <= limit; candadate += 2) {
    if (nonprimes.has(candadate)) continue

    yield candadate

    for (let mark = candadate * candadate; mark <= limit; mark += candadate) {
      nonprimes.add(mark)
    }
  }
}

Tags:

construct:assignment
construct:big-int
construct:comment
construct:const
construct:constructor
construct:continue
construct:for-loop
construct:function
construct:if
construct:implicit-conversion
construct:invocation
construct:lambda
construct:let
construct:method
construct:multiply
construct:number
construct:object
construct:parameter
construct:property
construct:return
construct:set
construct:template-string
construct:typedef
construct:variable
construct:visibility-modifiers
construct:yield
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:looping
technique:laziness
uses:Set
iHiD commented 1 year ago

Exercise: legacy-difference-of-squares

Code

'use strict'

module.exports = Squares

function Squares (upto) {
  this.squareOfSums = Math.pow(upto * (upto + 1) / 2, 2)
  this.sumOfSquares = upto * (upto + 1) * (2 * upto + 1) / 6
  this.difference = this.squareOfSums - this.sumOfSquares
}

Tags:

construct:add
construct:assignment
construct:divide
construct:implicit-conversion
construct:method
construct:multiply
construct:number
construct:parameter
construct:subtract
construct:use-strict
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:bit-manipulation
technique:bit-shifting
technique:math:bit-manipulation
technique:math:bit-shifting
iHiD commented 1 year ago

Exercise: legacy-kindergarten-garden

Code

'use strict'

module.exports = Garden

var NAMES = [
  'Alice',
  'Bob',
  'Charlie',
  'David',
  'Eve',
  'Fred',
  'Ginny',
  'Harriet',
  'Ileana',
  'Joseph',
  'Kincaid',
  'Larry'
]
var SEEDS = {
  G: 'grass',
  C: 'clover',
  R: 'radishes',
  V: 'violets'
}
var WIDTH = 2
var DELIM = '\n'

function Garden (diagram, names) {
  var length = diagram.indexOf(DELIM)
  var offset = length + DELIM.length

  names = (names || NAMES).slice().sort()

  for (var i = 0; i < length / WIDTH; i++) {
    var pos = i * WIDTH

    this[names[i].toLowerCase()] =
      plot(diagram.substr(pos, WIDTH) + diagram.substr(offset + pos, WIDTH))
  }
}

function plot (letters) {
  var plot = []

  for (var i = 0; i < letters.length; i++) {
    plot.push(SEEDS[letters[i]])
  }

  return plot
}

Tags:

construct:add
construct:assignment
construct:comment
construct:divide
construct:for-loop
construct:function
construct:implicit-conversion
construct:index
construct:invocation
construct:method
construct:multiply
construct:number
construct:object
construct:parameter
construct:return
construct:string
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:looping
iHiD commented 1 year ago

Exercise: legacy-binary-search

Code

function isSorted(arr){
  return arr.every(function(el, ii){
    return ii === 0 || el >= arr[ii-1];
  })
}
var Search = module.exports = function(data){
  isSorted(data) ? this.array=data : {};
};

Search.prototype.indexOf = function(target, lowerBound, upperBound){
  upperBound = upperBound || this.array.length-1;
  lowerBound = lowerBound || 0;
  searchIndex = lowerBound + Math.ceil((upperBound-lowerBound)/2);
  var el = this.array[searchIndex];
  if (el === target) return searchIndex;
  else if (upperBound === lowerBound && el !== target) return -1;

  el > target ? upperBound = searchIndex : lowerBound = searchIndex;
  return this.indexOf(target, lowerBound, upperBound);
};

Tags:

construct:add
construct:assignment
construct:boolean
construct:class
construct:divide
construct:field
construct:function
construct:if
construct:implicit-conversion
construct:index
construct:invocation
construct:logical-and
construct:logical-or
construct:method
construct:number
construct:parameter
construct:prototype
construct:return
construct:subtract
construct:ternary
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:recursion
iHiD commented 1 year ago

Exercise: legacy-custom-set

Code

var CustomSet = function(data = []) {
    this.data = data.filter(function(x, i) { return data.indexOf(x) === i; });
};

CustomSet.prototype.size = function() { return this.data.length; };

CustomSet.prototype.empty = function() { return this.size() === 0; };

CustomSet.prototype.contains = function(x) { return this.data.indexOf(x) >= 0; };

CustomSet.prototype.toList = function(x) { return this.data; };

CustomSet.prototype.subset = function(customSet) {
    return customSet.toList().filter(function(x) { return !this.contains(x); }, this).length === 0;
};

CustomSet.prototype.disjoint = function(customSet) {
    return this.toList().reduce(function(p, c) { return p && !customSet.contains(c); }, true);
};

CustomSet.prototype.eql = function(customSet) {
    return this.subset(customSet) && customSet.subset(this);
};

CustomSet.prototype.add = function(x) {
    if (!this.contains(x)) this.data.push(x);
    return this;
};

CustomSet.prototype.intersection = function(customSet) {
    return new CustomSet(this.toList().filter(function(x) { return customSet.contains(x); }));
};

CustomSet.prototype.difference = function(customSet) {
    return new CustomSet(this.toList().filter(function(x) { return !customSet.contains(x); }));
};

CustomSet.prototype.union = function(customSet) {
    return new CustomSet(this.toList().concat(customSet.toList()));
};

CustomSet.prototype.clear = function() {
    this.data = [];
    return this;
};

module.exports = CustomSet;

Tags:

construct:assignment
construct:boolean
construct:class
construct:constructor
construct:default-argument
construct:filter
construct:function
construct:if
construct:implicit-conversion
construct:index
construct:invocation
construct:logical-and
construct:method
construct:number
construct:parameter
construct:prototype
construct:return
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:higher-order-functions
iHiD commented 1 year ago

Exercise: legacy-collatz-conjecture

Code

class CC {
    steps(no) {
        if(no <= 0) throw new Error('Only positive numbers are allowed')

        let step = 0
        for(;no -1; step++)
            no = no%2? 3*no +1: no /2
        return step
    }
}

module.exports = CC

Tags:

construct:add
construct:assignment
construct:class
construct:constructor
construct:division
construct:for-loop
construct:if
construct:implicit-conversion
construct:method
construct:multiply
construct:number
construct:parameter
construct:return
construct:ternary
construct:throw
construct:throw-expression
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:looping
iHiD commented 1 year ago

Exercise: scale-generator

Code

// Chromatic
// A, A#, B, C, C#, D, D#, E, F, F#, G, G#
// A, Bb, B, C, Db, D, Eb, E, F, Gb, G, Ab

// No Sharps or Flats: C major a minor
// Use Sharps: G, D, A, E, B, F# major e, b, f#, c#, g#, d# minor
// Use Flats: F, Bb, Eb, Ab, Db, Gb major d, g, c, f, bb, eb minor

const CHROMATIC_WITH_SHARPS = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'];
const CHROMATIC_WITH_FLATS = ['A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab'];
const NO_SHARPS_NO_FLATS = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];

export class Scale {
  constructor(tonic) {
    this.tonic = tonic;
    let adjustedTonic = tonic[0].toUpperCase() + tonic.slice(1, tonic.length);
    let scale;
    if (['C', 'a', 'G', 'D', 'A', 'E', 'B', 'F#', 'b', 'f#', 'c#', 'g#', 'd#'].includes(tonic)) scale = [...CHROMATIC_WITH_SHARPS.slice(CHROMATIC_WITH_SHARPS.indexOf(adjustedTonic), CHROMATIC_WITH_SHARPS.length), ...CHROMATIC_WITH_SHARPS.slice(0, CHROMATIC_WITH_SHARPS.indexOf(adjustedTonic))];
    else scale = [...CHROMATIC_WITH_FLATS.slice(CHROMATIC_WITH_FLATS.indexOf(adjustedTonic), CHROMATIC_WITH_FLATS.length), ...CHROMATIC_WITH_FLATS.slice(0, CHROMATIC_WITH_FLATS.indexOf(adjustedTonic))];

    this.scale = scale;
    // this.chromaticScaleWithSharps = [...CHROMATIC_WITH_SHARPS.slice(CHROMATIC_WITH_SHARPS.indexOf(tonic), CHROMATIC_WITH_SHARPS.length), ...CHROMATIC_WITH_SHARPS.slice(0, CHROMATIC_WITH_SHARPS.indexOf(tonic))];

    // this.chromaticScaleWithFlats = [...CHROMATIC_WITH_FLATS.slice(CHROMATIC_WITH_FLATS.indexOf(tonic), CHROMATIC_WITH_FLATS.length), ...CHROMATIC_WITH_FLATS.slice(0, CHROMATIC_WITH_FLATS.indexOf(tonic))];
  }

  chromatic() {
    return this.scale;
  }

  interval(intervals) {
    let scale = [];
    scale.push(this.scale[0]);
    let i = 0;
    [...intervals].map((l) => {
      switch (l) {
        case 'm':
          i += 1;
          if (i < this.scale.length) scale.push(this.scale[i]);
          break;
        case 'M':
          i += 2;
          if (i < this.scale.length) scale.push(this.scale[i]);
          break;
        case 'A':
          i += 3;
          if (i < this.scale.length) scale.push(this.scale[i]);
          break;
      }
    })
    return scale;
  }
}

Tags:

construct:add
construct:assignment
construct:break
construct:class
construct:comment
construct:constructor
construct:const
construct:if
construct:implicit-conversion
construct:index
construct:initializer
construct:invocation
construct:lambda
construct:let
construct:method
construct:number
construct:parameter
construct:return
construct:string
construct:switch
construct:throw
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:higher-order-functions
iHiD commented 1 year ago

Exercise: grep

Code

#!/usr/bin/env node

const fs = require('fs');
const path = require("path");
const readline = require('readline');

// replicate minimist
const args = process.argv.slice(2);
const argv = { _: [] };

while(args.length) {
    const arg = args.shift();

    if (arg.startsWith('-')) {
        argv[arg[1]] = true;
    }
    else {
        argv._.push(arg);
    }
}

// K, now we start

let pattern = argv._[0];
const files = argv._.slice(1);

const several_files = files.length > 1;
const case_sensitive = !argv.i;

if (!case_sensitive) {
    pattern = pattern.toLowerCase();
}

// to be called once per input file
function next() {
    if (files.length <= 0) return;

    const filename = files.shift();
    const full_path = path.resolve(__dirname, filename);

    let match_count = 0;
    let no_match_count = 0;
    let line_number = 0;

    const rl = readline.createInterface({
        input: fs.createReadStream(filename),
        output: null,
        console: false
    });

    rl.on('line', input => {
        line = case_sensitive ? input : input.toLowerCase()
        line_number++;

        const match = argv.x
            ? (line === pattern)
            : line.includes(pattern)
        ;

        if (match) {
            match_count++;
        }
        else {
            no_match_count++;
        }

        if (argv.l) return;

        const should_print = argv.v ? !match : match;

        if (should_print) {
            console.log(`${several_files ? `${full_path}:` : ''}${argv.n ? `${line_number}:` : ''}${input}`);
        }
    });

    rl.on('close', () => {
        if (argv.l) {
            const should_print = argv.v ? no_match_count : match_count;

            if (should_print) {
                console.log(filename);
            }
        }

        next();
    });
}

next();

Tags:

construct:assignment
construct:comment
construct:const
construct:constructor
construct:continue
construct:expression-templates
construct:fat-arrow-function
construct:if
construct:implicit-conversion
construct:indexed-access
construct:invocation
construct:let
construct:method
construct:nested-function
construct:null
construct:nullability
construct:number
construct:object
construct:optional-parameter
construct:parameter
construct:return
construct:string
construct:ternary
construct:template-string
construct:throw
construct:variable
construct:visibility-modifiers
construct:while-loop
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:higher-order-functions
technique:looping
ErikSchierboom commented 12 months ago

This is an automated comment

Hello :wave: Next week we're going to start using the tagging work people are doing on these. If you've already completed the work, thank you! If you've not, but intend to this week, that's great! If you're not going to get round to doing it, and you've not yet posted a comment letting us know, could you please do so, so that we can find other people to do it. Thanks!