Best JavaScript code snippet using storybook-root
day16.ts
Source:day16.ts
1// Helpers for animations2import { Instance as Chalk } from "chalk";3const chalk = new Chalk();4const sleep = async () => await new Promise((resolve, reject) => setTimeout(resolve, 1));5import { data as input } from "./data/day16.data";6let debug = true;7// const data = "D2FE28"; // // Part 1 - Example 18// const data = "38006F45291200"; // // Part 1 - Example 2 - Pass9// const data = "EE00D40C823060"; // // Part 1 - Example 3 - Pass10// const data = "8A004A801A8002F478"; // // Part 1 - Example 4 - Pass - Version = 1611// const data = "620080001611562C8802118E34"; // // Part 1 - Example 5 - Pass - Version = 1212// const data = "C0015000016115A2E0802F182340"; // // Part 1 - Example 6 - Pass - Version sum = 2313// const data = "A0016C880162017C3686B18A3D4780"; // // Part 1 - Example 7 - Pass - Version sum = 3114// const data = "C200B40A82"; // // Part 2 - Example 1 - Pass - Returning 315// const data = "04005AC33890"; // // Part 2 - Example 2 - Pass - Returning (tests product) 54.16// const data = "880086C3E88112"; // // Part 2 - Example 3 - Pass Return (tests min) 7.17// const data = "CE00C43D881120"; // // Part 2 - Example 4 - Pass Return (tests max) 9.18// const data = "D8005AC2A8F0"; // // Part 2 - Example 5 - Pass Return (tests less than) 1.19// const data = "F600BC2D8F"; // // Part 2 - Example 6 - Pass Return (tests more than) 0.20// const data = "9C005AC2F8F0"; // // Part 2 - Example 7 - Pass Return (tests equals) 021// const data = "9C0141080250320F1802104A08" // // Part 2 - Example 8- Pass Return (tests equals) 122// Live data23const data = input;24let packetId = 0;25class Packet {26 protected id: number;27 constructor(28 public version: number = null,29 public typeID: number = null,30 // Type 1 propertes31 public literalValues: string[] = [],32 public literalValue: number = null,33 // Type 6 properties34 public lengthType: number = null,35 public lengthTypeValue: number = null,36 // Shared37 public subpackets: Packet[] = []38 ) {39 this.id = packetId++;40 }41 public setVersion(version: number) {42 if (debug) {43 console.log(`[${this.id}] Setting: 'version' to '${version}'`);44 }45 this.version = version;46 }47 public setTypeID(typeID: number) {48 if (debug) {49 console.log(`[${this.id}] Setting: 'typeID' to '${typeID}'`);50 }51 this.typeID = typeID;52 }53 public setLiteralValues(literalValues: string[]) {54 if (debug) {55 console.log(`[${this.id}] Setting: 'literalValues' to '${literalValues}'`);56 }57 this.literalValues = literalValues;58 }59 public setLiteralValue(literalValue: number) {60 if (debug) {61 console.log(`[${this.id}] Setting: 'literalValue' to '${literalValue}'`);62 }63 this.literalValue = literalValue;64 }65 public setLengthType(lengthType: number) {66 if (debug) {67 console.log(`[${this.id}] Setting: 'lengthType' to '${lengthType}'`);68 }69 this.lengthType = lengthType;70 }71 public setLengthTypeValue(lengthTypeValue: number) {72 if (debug) {73 console.log(`[${this.id}] Setting: 'lengthTypeValue' to '${lengthTypeValue}'`);74 }75 this.lengthTypeValue = lengthTypeValue;76 }77 public setSubpackets(subpackets: Packet[]) {78 if (debug) {79 console.log(`[${this.id}] Setting: 'subpackets' to '${subpackets}'`);80 }81 this.subpackets = subpackets;82 }83 public render(indentAmount = 0) {84 const indentCharacter = " ";85 let indent = [...new Array(indentAmount)].map(() => indentCharacter).join("");86 const isLiteral = this.typeID == 4;87 let detail = ""88 if (isLiteral) {89 detail = `${this.literalValue} (${this.literalValues.join(", ")})`;90 } else {91 detail = `Length Type: ${this.lengthType} ${this.lengthType == 11 ? "(Number of subpackets " + this.subpackets.length.toString() + ")" : "(Total bits)"}, Type Value: ${this.lengthTypeValue}`92 }93 console.log(`${indent}${indentAmount > 0 ? "âââ " : ""}V: ${this.version}, ID: ${this.typeID} (${this.typeID == 4 ? "Literal" : "Operator"}), ${detail}`);94 for (let child of this.subpackets) {95 child.render(indentAmount + 1);96 }97 }98 public versionSum() {99 return this.subpackets100 .map(subpacket => subpacket.versionSum())101 .reduce((a, b) => a + b, this.version);102 }103 // Part 2 Operate104 public operate(): number {105 switch (this.typeID) {106 // Sum107 case 0:108 return this.subpackets109 .map(subpacket => subpacket.operate())110 .reduce((a, b) => {111 console.log(`${a} + ${b} = ${a+b}`);112 return a + b;113 }, 0);114 // Product115 case 1:116 return this.subpackets117 .map(subpacket => subpacket.operate())118 .reduce((a, b) => {119 console.log(`${a} * ${b} = ${a*b}`);120 return a * b;121 }, 1);122 // Min123 case 2:124 return this.subpackets125 .map(subpacket => subpacket.operate())126 .reduce((a, b) => {127 console.log(`min(${a},${b}) = ${Math.min(a,b)}`);128 return Math.min(a, b);129 }, Number.MAX_SAFE_INTEGER);130 // Max131 case 3:132 return this.subpackets133 .map(subpacket => subpacket.operate())134 .reduce((a, b) => {135 console.log(`max(${a},${b}) = ${Math.max(a,b)}`);136 return Math.max(a, b);137 }, 0);138 // Literal value139 case 4:140 console.log(`literal(${this.literalValues.join("")}) = ${this.literalValue}`);141 return this.literalValue;142 // Greater than143 case 5:144 case 6:145 case 7:146 const a = this.subpackets[0].operate();147 const b = this.subpackets[1].operate();148 switch(this.typeID) {149 case 5:150 console.log(`${this.typeID} //${a} > ${b} = ${a > b ? 1 : 0}`);151 return a > b ? 1 : 0;152 // Less than153 case 6:154 console.log(`${a} < ${b} = ${a < b ? 1 : 0}`);155 return a < b ? 1 : 0;156 // Equal157 case 7:158 console.log(`${a} == ${b} = ${a == b ? 1 : 0}`);159 return a == b ? 1 : 0;160 }161 }162 return 0;163 }164}165let decode = async (input: string[], packetCap = -1) => {166 // Clone input internally as we keep slicing against it167 let binary = [...input];168 // Set up packet tree169 let outputPackets = [] as Packet[];170 let initialInputSize = binary.length;171 while (binary.length > 7 && (packetCap < 0 || outputPackets.length < packetCap)) {172 const currentPacket = new Packet();173 // Packet version174 currentPacket.setVersion(parseInt(binary.splice(0, 3).join(""), 2));175 // Packet type id176 currentPacket.setTypeID(parseInt(binary.splice(0, 3).join(""), 2));177 // Literal packet178 if (currentPacket.typeID == 4) {179 // Remove first letter for comparison180 while (binary.splice(0, 1).join("") == "1") {181 // Remove next 4 for value182 currentPacket.setLiteralValues([...currentPacket.literalValues, binary.splice(0, 4).join("")]);183 }184 // Remove last 5, only keep last 4 - While above ending on a 0 would splice that 0 away185 currentPacket.setLiteralValues([...currentPacket.literalValues, binary.splice(0, 4).join("")]);186 // Calculate actual value187 currentPacket.setLiteralValue(parseInt(currentPacket.literalValues.join(""), 2));188 }189 // Operator packets190 else {191 // Length type : 0 = Next 15 bits state the size of all sub packets, 11 means next bits state number of sub packets 192 currentPacket.setLengthType(binary.splice(0, 1).join("") == "0" ? 15 : 11);193 // Remove next 11 or 15 bytes194 currentPacket.setLengthTypeValue(parseInt(binary.splice(0, currentPacket.lengthType).join(""), 2));195 if (currentPacket.lengthType == 15) {196 // Now we know the subpacket size197 const subpackets = binary.splice(0, currentPacket.lengthTypeValue);198 // Passing reference on purpose here199 const result = await decode(subpackets);200 currentPacket.subpackets = result.packets;201 } else if (currentPacket.lengthType == 11) {202 // We process the data - Passing in a reference against203 const result = await decode(binary, currentPacket.lengthTypeValue);204 currentPacket.subpackets = result.packets;205 // Slice off once we know how much characters we have processed206 binary.splice(0, result.charactersProcessed);207 } else {208 console.error(`Invalid length type ${currentPacket.lengthType}`);209 process.exit();210 }211 }212 outputPackets.push(currentPacket);213 }214 return {215 packets: outputPackets,216 charactersProcessed: initialInputSize - binary.length217 };218};219(async () => {220 // Convert hex to binary221 // Sensible way - not applicable for this puzzle, ensure each hex is converted to binary indivudually222 let binary = data223 .split("")224 .map(character => parseInt(character, 16).toString(2).padStart(4, "0"))225 .join("")226 .split("");227 // Decode228 console.log("")229 console.log(`Hex: ${data}`);230 console.log(`Binary: ${binary.join("")}`);231 console.log("======= Operations =========");232 const resultingPackets = await decode(binary);233 console.log("============================");234 console.log("Final results: ")235 if (debug) {236 console.log(resultingPackets.packets);237 for (let resultPacket of resultingPackets.packets) {238 resultPacket.render();239 }240 }241 console.log(" - Version sum: ")242 console.log(resultingPackets.packets.map(packet => packet.versionSum()).reduce((a, b) => a + b, 0));243 console.log(" - Operational value: ")244 console.log(resultingPackets.packets.map(packet => packet.operate()));...
day16.mjs
Source:day16.mjs
1import { getTask } from "./lib.js";2const task = await getTask(16);3// const task = `D2FE28`;4// const task = `38006F45291200`;5// const task = `EE00D40C823060`;6// const task = `8A004A801A8002F478`;7// const task = `620080001611562C8802118E34`;8// const task = `C0015000016115A2E0802F182340`;9// const task = `A0016C880162017C3686B18A3D4780`;10// const task = `C200B40A82`;11// const task = `04005AC33890`;12// const task = `880086C3E88112`;13// const task = `CE00C43D881120`;14// const task = `D8005AC2A8F0`;15// const task = `F600BC2D8F`;16// const task = `9C005AC2F8F0`;17// const task = `9C0141080250320F1802104A08`;18const bits = task19 .split("")20 .map((hex) => parseInt(hex, 16).toString(2).padStart(4, "0"))21 .join("");22const SUM = 0;23const PRODUCT = 1;24const MINIMUM = 2;25const MAXIMUM = 3;26const LITERAL_VALUE = 4;27const GREATER_THAN = 5;28const LESS_THAN = 6;29const EQUAL_TO = 7;30let position = 0;31let versionSum = 0;32const toBinary = (bitsArray) => {33 return parseInt(bitsArray.join(""), 2);34};35const processLiteralValue = (bits) => {36 let literalValueBinary = "";37 while (position < bits.length) {38 const [prefix, ...group] = bits.splice(0, 5);39 literalValueBinary += group.join("");40 if (prefix === "0") {41 // Last group42 break;43 }44 }45 const literalValue = parseInt(literalValueBinary, 2);46 console.log(` Literal value is ${literalValue}`);47 return literalValue;48};49const processOperator = (operator, bits) => {50 const lengthTypeID = toBinary(bits.splice(0, 1));51 if (lengthTypeID === 0) {52 console.log(` Length Type ID ${lengthTypeID} => 15 bits`);53 const numberOfBits = toBinary(bits.splice(0, 15));54 console.log(` Sub-packet bits ${numberOfBits}`);55 const subPacket = bits.splice(0, numberOfBits);56 let literalValues = [];57 while (subPacket.length > 0) {58 literalValues.push(processPacket(subPacket));59 }60 const result = calcResult(operator, literalValues);61 return result;62 } else {63 console.log(` Length Type ID ${lengthTypeID} => 11 bits`);64 const numberOfSubPackets = toBinary(bits.splice(0, 11));65 console.log(` Number of sub packets ${numberOfSubPackets}`);66 let literalValues = [];67 for (let i = 0; i < numberOfSubPackets; i++) {68 literalValues.push(processPacket(bits));69 }70 const result = calcResult(operator, literalValues);71 return result;72 }73};74const processPacket = (bits) => {75 if (bits.length === 0 || toBinary(bits.slice(position)) === 0) {76 return;77 }78 const version = toBinary(bits.splice(0, 3));79 versionSum += version;80 const typeId = toBinary(bits.splice(0, 3));81 console.log(`Packet version ${version}`);82 if (typeId === LITERAL_VALUE) {83 console.log(`${typeId} => Packet is literal value`);84 const literalValue = processLiteralValue(bits);85 return literalValue;86 } else {87 console.log(`${typeId} => Packet is operator`);88 const result = processOperator(typeId, bits);89 return result;90 }91};92const calcResult = (operator, literalValues) => {93 let operatorResult;94 switch (operator) {95 case SUM:96 operatorResult = literalValues.reduce((prev, value) => prev + value, 0);97 break;98 case PRODUCT:99 operatorResult = literalValues.reduce((prev, value) => prev * value, 1);100 break;101 case MINIMUM:102 operatorResult = Math.min(...literalValues);103 break;104 case MAXIMUM:105 operatorResult = Math.max(...literalValues);106 break;107 case GREATER_THAN:108 operatorResult = literalValues[0] > literalValues[1] ? 1 : 0;109 break;110 case LESS_THAN:111 operatorResult = literalValues[0] < literalValues[1] ? 1 : 0;112 break;113 case EQUAL_TO:114 operatorResult = literalValues[0] === literalValues[1] ? 1 : 0;115 break;116 }117 console.log(`Operator ${GREATER_THAN} result is ${operatorResult}`);118 return operatorResult;119};120const result = processPacket(bits.split(""));121console.log(122 `--- Part One ---\nWhat do you get if you add up the version numbers in all packets?\n${versionSum}`123);124console.log(125 `--- Part Two ---\nWhat do you get if you evaluate the expression represented by your hexadecimal-encoded BITS transmission?\n${result}`...
WhereQuery.ts
Source:WhereQuery.ts
1import type { Entity, NotEntityBrand } from '../Entity';2import type { ExcludeEntityCollections, ExcludeFunctions } from '../types';3type ExcludeUndefined<T> = Exclude<T, undefined>;4export type LiteralValues<TValue> = (ExcludeUndefined<TValue> | null)[] | ExcludeUndefined<TValue> | null;5export type WhereClauseValue<TValue> = TValue extends NotEntityBrand | undefined6 ? Exclude<TValue, NotEntityBrand | undefined> // If the value is a NotEntityBrand, return the type without undefined7 : Extract<TValue, Entity> extends undefined // Otherwise if the type does not extend Entity8 ? LiteralValues<TValue>9 :10 | (ExcludeUndefined<Exclude<TValue, Entity>> | null)[] // Allow an array of the literal value (non-entity)11 | (Pick<Extract<ExcludeUndefined<TValue>, Entity>, 'id'> | null)[] // Allow an array of objects with the id property12 | ExcludeUndefined<Exclude<TValue, Entity>> // Allow a single literal value13 | Pick<Extract<ExcludeUndefined<TValue>, Entity>, 'id'> // Allow a single object with the id property14 | null;15export type StringConstraint<TValue extends string> = {16 [P in 'contains' | 'endsWith' | 'like' | 'startsWith']?: LiteralValues<TValue>;17};18export type NumberOrDateConstraint<TValue extends Date | number> = {19 [P in '<' | '<=' | '>' | '>=']?: LiteralValues<TValue>;20};21export type NegatableConstraint<TValue> =22 | TValue23 | {24 '!': TValue;25 };26export type WhereQueryStatement<TValue> = TValue extends string27 ? NegatableConstraint<StringConstraint<TValue> | WhereClauseValue<TValue>>28 : TValue extends Date | number29 ? NegatableConstraint<NumberOrDateConstraint<TValue> | WhereClauseValue<TValue>>30 : NegatableConstraint<WhereClauseValue<TValue>>;31export type WhereQuery<T extends Entity> = {32 // Exclude entity collections and functions. Make the rest of the properties optional33 [K in keyof T as ExcludeEntityCollections<T[K], ExcludeFunctions<T[K], K>>]?: K extends 'id'34 ? WhereQueryStatement<T | T[K]> // Allow nested where query statements35 : T[K] extends (infer U)[] | undefined // If property type is an array, allow where query statements for the array type36 ? WhereQueryStatement<U>37 :38 | (ExcludeUndefined<T[K]> | null)[] // Allow array of type39 | T[K] // Allow Single object of type40 | WhereQueryStatement<T[K]> // Allow nested where query statements41 | { '!': LiteralValues<T[K]> }; // Allow arrays of union types42} & {43 or?: WhereQuery<T>[];...
Using AI Code Generation
1const { literalValues } = require('storybook-root');2const literalValues = require('storybook-root').literalValues;3import { literalValues } from 'storybook-root';4import literalValues from 'storybook-root';5import * as literalValues from 'storybook-root';6import { literalValues } from 'storybook-root';7import literalValues from 'storybook-root';8import * as literalValues from 'storybook-root';9import { literalValues } from 'storybook-root';10import { literalValues } from 'storybook-root';11import { literalValues } from 'storybook-root';12import literalValues from 'storybook-root';13import literalValues from 'storybook-root';14import literalValues from 'storybook-root';15import * as literalValues from 'storybook-root';16import * as literalValues from 'storybook-root';17import * as literalValues from 'storybook-root';18import { literalValues } from 'storybook-root';19import literalValues from 'storybook-root';20import * as literalValues from 'storybook-root';21import { literalValues } from 'storybook-root';22import literalValues from 'storybook-root';23import * as literalValues from 'storybook-root';24import { literalValues } from 'storybook-root';25import literalValues from 'storybook-root';26import * as literalValues from 'storybook-root';27import { literalValues } from 'storybook-root';28import literalValues from 'storybook-root';29import * as literalValues from 'storybook-root';30import { literalValues } from 'storybook-root';31import literalValues from 'storybook-root';32import * as literalValues from 'storybook-root';33import { literalValues } from 'storybook-root';34import literalValues from 'storybook-root';35import * as literalValues from 'storybook-root';
Using AI Code Generation
1import { literalValues } from 'storybook-root-wrapper'2const literalValues = require('storybook-root-wrapper').literalValues3import { literalValues } from 'storybook-root-wrapper'4const literalValues = require('storybook-root-wrapper').literalValues5import { literalValues } from 'storybook-root-wrapper'6const literalValues = require('storybook-root-wrapper').literalValues7import { literalValues } from 'storybook-root-wrapper'8const literalValues = require('storybook-root-wrapper').literalValues9import { literalValues } from 'storybook-root-wrapper'10const literalValues = require('storybook-root-wrapper').literalValues11import { literalValues } from 'storybook-root-wrapper'12const literalValues = require('storybook-root-wrapper').literalValues13import { literalValues } from 'storybook-root-wrapper'14const literalValues = require('storybook-root-wrapper').literalValues15import { literalValues } from 'storybook-root-wrapper'16const literalValues = require('storybook-root-wrapper').literalValues17import { literalValues } from 'storybook-root-wrapper'18const literalValues = require('storybook-root-wrapper').literalValues19import { literalValues } from 'storybook-root-wrapper'
Using AI Code Generation
1const { literalValues } = require('storybook-root');2const { expect } = require('chai');3describe('literalValues', () => {4 it('returns an array of values', () => {5 expect(literalValues).to.be.an('array');6 });7});8const { addDecorator } = require('@storybook/react');9const { withRoot } = require('storybook-root');10addDecorator(withRoot);11const { setRoot } = require('storybook-root');12module.exports = (baseConfig, env) => {13 setRoot(__dirname);14 return baseConfig;15};16require('storybook-root/register');17import { addons } from '@storybook/addons';18import { withRoot } from 'storybook-root';19addons.setConfig({20});21import { withRoot } from 'storybook-root';22export const decorators = [withRoot];23 window.STORYBOOK_ROOT = __dirname;24 window.STORYBOOK_ROOT = __dirname;25 window.STORYBOOK_ROOT = __dirname;
Using AI Code Generation
1import { literalValues } from 'storybook-root';2import { storiesOf } from '@storybook/react';3storiesOf('literalValues', module).add('literalValues', () => {4 return (5 <p>{literalValues}</p>6 );7});8import { configure } from '@storybook/react';9import { setOptions } from '@storybook/addon-options';10setOptions({
Using AI Code Generation
1import { literalValues } from 'storybook-root';2export default {3 argTypes: {4 backgroundColor: { control: 'color' },5 size: {6 control: {7 options: literalValues('small', 'medium', 'large'),8 },9 },10 },11};12import { literalValues } from 'storybook-root';13export default {14 argTypes: {15 backgroundColor: { control: 'color' },16 size: {17 control: {18 options: literalValues('small', 'medium', 'large'),19 },20 },21 },22};23import { literalValues } from 'storybook-root';24export default {25 argTypes: {26 backgroundColor: { control: 'color' },27 size: {28 control: {29 options: literalValues('small', 'medium', 'large'),30 },31 },32 },33};34import { literalValues } from 'storybook-root';35export default {36 argTypes: {37 backgroundColor: { control: 'color' },38 size: {39 control: {40 options: literalValues('small', 'medium', 'large'),41 },42 },43 },44};45import { literalValues } from 'storybook-root';46export default {47 argTypes: {48 backgroundColor: { control: 'color' },49 size: {50 control: {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!